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

150
Views
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 answers
Answer question

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 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!