I want to update object all elements one by one in map, It is updating only one element of the object not all
const [docUrls, setDocUrls] = useState({
imageUrl: "", panUrl: "",statementUrl: ""
})
response from api
res.data.map(item=>{
if(item.type === 'image'){
setDocUrls({...docUrls, imageUrl:item.url})
}else if(item.type === 'pan'){
setDocUrls({...docUrls, panUrl:item.url})
}else
setDocUrls({...docUrls, statementUrl:item.url})
}})
>Solution :
setDocUrls is asynchronous so you’re just overwriting docUrls everytime you call it.
Having multiple setDocUrls({...docUrls, imageUrl:item.url}) will just keep overwriting the previous call due to the ...docUrls.
Instead, make a copy of docUrl.
const docUrlCopy = { ...docUrls }
res.data.map(item=>{
if(item.type === 'image'){
docUrlCopy.imageUrl = item.url
}else if(item.type === 'pan'){
docUrlCopy.panUrl = item.url
}else
docUrlCopy.statementUrl = item.url
}})
setDocUrls(docUrlCopy) // only 1 call