I recently started learning react.js for making my final year project using MERN stack during this i am facing this issue, i.e. 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?
CodePudding user response:
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
CodePudding user response:
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