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.
`
>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.