I’m working on a project in react using graphql. I have an object
const [additionalInfo, setAdditionalInfo] = useEffect({}),
which contains objects that have been selected. On this screen, I have data that is coming from my backend, which looks like: {status: "single", work:"full-time", etc...} that I need to add to my additionalInfo object if it contains a "!" (signifies that it was previously selected). I’ve been trying to do this using a useEffect, but I’m having some issues.
useEffect(()=> {
for (var item in meDataData?.lifeStyle) {
if ( meDataData?.lifeStyle[item]?.includes('!')) {
setAdditionalInfo(
....additionalInfo,
[item]: meDataData?.lifeStyle[item]?.substring(0,
meDataData?.lifeStyle[item]?.length - 1)
})
}
}
}, [meDataData?.lifeStyle])
where meDataData?.lifeStyle = {status: "single!", work:"full time!", dependents:"none", "higherEducation": null,}only gives me additionalInfo = {work:"full time"}. After searching for solutions and answers for why the spreader wasn’t working I tried:
useEffect(()=> {
for (var item in meDataData?.lifeStyle) {
if ( meDataData?.lifeStyle[item]?.includes('!')) {
setAdditionalInfo(prevState =>{
return ({
...prevState,
[item]: meDataData?.lifeStyle[item]?.substring(0, meDataData?.lifeStyle[item]?.length - 1)
})
})
}
}
}, [meDataData?.lifeStyle])
which gave me additionalInfo = {status:"single", higherEducation:undefined}. Does anyone know why I am having this problem? I would really appreciate any help or advice on how to solve this problem. Thank you!
>Solution :
Create a new object and update it inside the loop before setting it into the state after the loop.
const newInfo = {...additionalInfo};
for (const [key, val] of Object.entries(meDataData?.lifeStyle ?? {}))
if (val?.includes('!'))
newInfo[key] = val.slice(0, -1);
setAdditionalInfo(newInfo);