Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda