John Doener
John Doener

Reputation: 119

How to push to a map value array and use it as state in React?

I have the following state in React:

const [tasksMap, setTasksMap] = useState(new Map());

with the following map creation:

tasks.forEach((task) => {
  const key = `${week.year}-${week.weekNo}`;

  if (!tasksMap.has(key)) {
    tasksMap.set(key, []);
  }
  tasksMap.get(key).push(task);
});

How can I set the map tasksMap as the React state?

setTasksMap(tasksMap.set(key, [])); works but has an empty array as value, which does not update when I run tasksMap.get(key).push(task);.

Upvotes: 1

Views: 1020

Answers (1)

Khabir
Khabir

Reputation: 5862

Please try this. Here I used separate variable to store data and set that variable into the state at last.

let mapObj = new Map();

tasks.forEach((task) => {
  const key = `${week.year}-${week.weekNo}`;

  if (!mapObj.has(key)) {
    mapObj.set(key, []);
  }
  mapObj.get(key).push(task);
});

setTasksMap(mapObj); 

Upvotes: 1

Related Questions