0

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
}
4
  • how about updating state by setResults([...newArray]) ? Commented Jan 2, 2022 at 10:45
  • oh my god you're a genious, thought ... was only for objects, and not for array Commented Jan 2, 2022 at 10:46
  • it's because in your manner, you are just mutating the previous value and react doesn't recognize any update in the state. in order to update your state, you need to pass new array to setResults method. Commented Jan 2, 2022 at 10:50
  • 1
    ... works for array and objecst. Here you can read more about it developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 2, 2022 at 10:51

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.