Search code examples
javascriptarraysreactjsuse-statearray-map

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>

Solution

  • 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
      );
    }