0

I have this default state :

const [manager, setManager] = useState([{ name: undefined, project: [] }]);

I have data coming from an API that looks like this :

[{name : 'John doe'} , {'jane' : doe}]

How do i update my state so it ends up looking like this after adding the data to the state :

[{ name: 'john doe', project: [] } , { name: 'jane doe', project: [] }]; 

I tried this :

setManager(prev => ([...prev , res.data]));
Kevin.a
  • 4,094
  • 8
  • 46
  • 82

1 Answers1

1

I'm assuming you mean you want to change this:

[{name : 'John doe'}, {name : 'Jane doe'}]

to something like this

[{ name: 'john doe', project: [] } , { name: 'jane doe', project: [] }];

In this snippet, you are spreading the existing data with the new data.

 setManager(prev => ([...prev, res.data]));

So in manager, you will get 2 arrays because you didn't spread the second one

[{ name: undefined, project: [] }, [{name : 'John doe'} , {name : 'Jane doe'}]]

In this case, also making the assumptions that your project key might not be empty, and you want to map the existing project with data inside each your api data.

I will do something like this

setManager(prevData => 
  resData.map(singleRes => {
    return {name: singleRes.name, project: prevData.project}
  })
)
wing
  • 155
  • 6