0

I have a state variable like this:

const [todos, setTodos] = useState([])

I want to put a lot of arrays into it (in an amount unknown to me). This is the code I wrote:

data.forEach(x => {
           const userId = x.userId;
           const to_to_user = data.filter(d=>d.userId===userId)
           setTodos({...todos, [userId]:to_to_user});
           });

The problem is that each round of a loop overruns the previous index and at the end of the array there is only the last index. Does anyone have a solution?

1 Answer 1

3

Technically, you can do this:

data.forEach(x => {
  const userId = x.userId;
  const to_to_user = data.filter(d=>d.userId===userId)
  setTodos((oldTodos) => {...oldTodos, [userId]:to_to_user}));
});

so that you always have the most up-to-date version of todos.

But instead of calling setTodos multiple times, you should instead create the object first and then call setTodos once.

const newTodos = data.reduce((obj, x) => {
  const userId = x.userId;
  const to_to_user = data.filter(d=>d.userId===userId);
  obj[userId] = to_to_user;
}, {});

setTodos((oldTodos) => {...oldTodos, ...newTodos});

Either way, the original line should be

const [todos, setTodos] = useState({});

because you're storing an object of arrays, not an array of objects or and array of arrays

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the answer! What is obj? What does he represent to me?
obj is short for object. Just a generic name like key and val (value) that I use when there's not really a good name to use there.
Yes, I understood that it is short for object, but I didn't understand, is it an array? object? I get an error like this: main.js:26 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting '0') at main.js:26:1 at Array.reduce (<anonymous>) at main.js:23:1
It turns out that the problem was in the obj name... I changed obj1 and everything worked out. Thank you for your quick response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.