I've got an API to work with where I first need to get a list of ids before calling APIs to get more details of each item.
I'm having trouble storing the result of the details in state. Somethings wrong with my understanding of the useState
lifecycle functionality.
Here's my code:
const MyComponent = () => {
const [details, setDetails] = useState({})
useEffect(() => {
api.getIds().then(res =>
res.data.ids.forEach(id =>
api.getDetails(id).then((res) => {
const newDetails = { ...details }
newDetails[id] = res.data.details
setDetails(newDetails)
})
)
)
}, [])
console.log(details)
...
}
In my results got api.getIds{}
I have 2 ids. What I'd expect in the console at the end of the render cycles is the following:
{ 1: <details for 1>, 2: <details for 2> }
Instead I get just:
{ 1: <details for 1> }
{ 2: <details for 2> }
Instead of updating the state object, it's being replaced. There's lifecycle stuff going on that prevents me from having the most up to date state in creating newDetails
.
How can I handle this properly?
Restrictions: I can't modify the API.