Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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, 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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!