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

152
Vistas
How to update the nested array using useState Hook in React

I am getting the error [The type cast expression is expected to be wrapped with parenthesis] Don't know how to update the nested array in useState.

let tempArray = [
  {
    filterType: "Company",
    dataList: []
  },
  {
    filterType: "Vehicle",
    dataList: ["Car", "Bike"]
  }
]

const [resultList, setResultList] = useState(tempArray)
const [indexChange, setIndexChange] = useState(0)

// Assume here I am using fetch request and getting the response.
if (responseJson.success) {
  setResultList(
    [
      ...resultList, 
      resultList[indexChange].dataList: responseJson.data
    ]
  )
}

Here I am rendering my result array. When clicking on the list! Based on the index, changes reflect.

<div className='filterTypeContainer' style={{ backgroundColor: "#F5F6F8", padding: "20px 20px", fontSize: 14, width: "40%" }}>
  { resultList.map((list, index) => { 
  return <div className='filerType' onClick={()=> setIndexChange(index)}>
    <p>{list.filterType}</p>
  </div>
  }) }
</div>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The method you're using is called the spread operator ...value. In this case it places all the items from the original state into a new array.

Use the spread operator to create a copy of the array. This prevents mutation to the original state. Then access the index in the array that you want to update and return the copied and updated state.

if (responseJson.success) {
  setResultList(resultList => {
    const copy = [...resultList]
    copy[indexChange].dataList = response.data
    return copy
  }
}

Alternatively you can use the .map method to loop over the state and return an updated object based on the index.

if (responseJson.success) {
  setResultList(resultList => resultList.map((item, index) =>
    index === indexChange ? ({
      ...item,
      dataList: responseJson.data
    }) : item
  );
}
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