简体   繁体   中英

how i can update the value of object of array by use state

I recently started learning react.js for making my final year project using MERN stack during this i am facing this issue, ie i have an array

let projectTech = ['js','node','react'];

and i want to concat it with technologies array present in following useState, please tell me how can i do it.

const [projectObj, setProjectObj] = useState({                 
        title: '',
        type: '',
        link: '',
        technologies:[],
        role:'',
        description: ''
    });

i already tried following combinations but it's not working, after console.log(projectObj.technologies) i got empty array.

setProjectObj({...projectObj,technologies: projectTech});
setProjectObj({...projectObj,technologies:[...projectTech]});
setProjectObj({...projectObj,technologies:[...projectObj.technologies,projectTech]});

please help me, how can i fix this?

You can try using the prevState of the setState function.

setProjectObj((prevState) => ({...prevState, technologies: projectTech }))

check out this: https://codesandbox.io/s/nifty-browser-wmoseu?file=/src/App.js

Nothing is wrong with that code. You only have to change how you console.log your result.

Since setting state is async, try to avoid logging state after setting it.

Add this in your component

const handleSetState = () => {
setProjectObj({...projectObj,technologies: projectTech});
console.log(projectObj) //WRONG, will console.log previous data
}

const handleSetState2 = () => {
const newObj = {...projectObj,technologies: projectTech}
setProjectObj(newObj);
console.log(newObj) //OK, but not actual state.
}

//BEST
useEffect(() => {
console.log(projectObj) //Console.log state
}, [projectObj]) //But only if state changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM