Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why setState doesn't rerender React page

I am having some datas from an API GET call,i store them in datas(so it’s not longer a string) and i want to delete some of them when the user choose some filters. I see the data change on the console and setState them but the page doesn’t update the new data.

const [datas, setData] = useState('');
const handleClick = (event) => {
    console.log("deleting")
    var newdata = datas
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

I used a new variable newdata because i saw that using the same variable data isn’t recommended.
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are mutating the content of the array.

Do this in handleClick instead:

const handleClick = (event) => {
    console.log("deleting")
    // Create a copy of datas, do not modify the original array
    var newdata = [...datas]
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

That would solve it because you’re creating a copy of the array with the spread operator ...

As a general rule, I’d always favor immutable array methods over mutable ones. You can check the docs for the methods and if it reads something like "changes the contents of an array", then the method is mutating the original array. Use methods that return a new copy of the array instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading