-2

This is the object, lets say I'm gonna add something inside list: [], how can I do that? I know like we can do it using the prevList callback but I'm kind of confused to map through it.

const [boardlist, setBoardlist] = useState([
    {
      id: 1,
      boardName: "home work",
      data: [
        {
          id: 1,
          header: "Stuff to do",
          list: [
            {
              id: 1,
              taskTitle: "working from home",
            },
          ],
        },
        {
          id: 2,
          header: "In Progress",
          list: [],
        },
        {
          id: 3,
          header: "Done",
          list: [],
        },
      ],
    },
  ]);

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
  • Does this answer your question? [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – Emile Bergeron Aug 27 '21 at 14:23
  • If navigating through this data structure is an issue, see: [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/q/11922383/1218980) – Emile Bergeron Aug 27 '21 at 14:24
  • Specifically for arrays in state: [Correct modification of state arrays in React.js](https://stackoverflow.com/q/26253351/1218980) – Emile Bergeron Aug 27 '21 at 14:24
  • Ya saw it, but I kinda still confused with the array I have, if I could get little bit help, it will really helpful. – Anonymous65 Aug 27 '21 at 14:25
  • You should include a clear use-case, what you have done to try and make it work ([mcve]) and what's not working. – Emile Bergeron Aug 27 '21 at 14:27
  • The problem is, when I use spread operators, it’s copies all the previous data, I’m not too sure to access into the particular index or object. – Anonymous65 Aug 27 '21 at 14:30
  • It really depends on how you identify the object you want to update. [By index](https://stackoverflow.com/q/8238456/1218980)? [By id](https://stackoverflow.com/q/7364150/1218980)? – Emile Bergeron Aug 27 '21 at 14:32
  • Ok let’s say I’m gonna add something into the object “list: []”, how do I remain all the previous data and only update the “list:”? – Anonymous65 Aug 27 '21 at 14:34
  • Since your state is an array and it seems you want to update a property of the first object within that state, take a look at: [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/q/28121272/1218980). – Emile Bergeron Aug 27 '21 at 14:39

1 Answers1

0

What about make a copy of the state and just push using the bracket notation and dot notation to reach the element that you need to change?

const boardlistCopy = JSON.parse(JSON.stringify(boardlist));
boardlistCopy[0].data[1].list.push({id: 2, task: "studying React"});
setBoardlist(boardlistCopy);
Simone Celli
  • 147
  • 2
  • 5