Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda