tony_merguez
tony_merguez

Reputation: 371

react setState doesn't update array value by index

does anybody know why updating specific index value like this doesn't work ?

const [results, setResults] = useState([...Array(data.length)].map(e => []));

const updateResults = (index, value) => { //value is for sur an array of one dimension
    let newArray = results;
    newArray[index] = value
    console.log(newArray) //verifying that it is OK (works well)
    setResults(newArray) //has no effect
}

Upvotes: 0

Views: 137

Answers (1)

Rugved Tipare
Rugved Tipare

Reputation: 68

React uses Object.is under the hood so that it knows when to re-render the component. To overcome this, use:

const [results, setResults] = useState([...Array(data.length)].map(e => []));

const updateResults = (index, value) => {
    let newArray = [...results]; // Object.is(results, newArray) will return false
    newArray[index] = value
    console.log(newArray)
    setResults(newArray)
}

Upvotes: 1

Related Questions