Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get UseEffect() to set State properly with spreader

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading