I want my React function to re-render after I splice an array.
Here Is (part of) the function (using Hooks):
function showProblem() {
const [andArray, setAndArray] = useState([]);
const deleteTag = (i, arr) => {
let and = andArray;
switch (arr) {
case "and":
and.splice(i, 1);
setAndArray(and);
break;
default:
return null;
}
};
return(
<div>
{andArray.map((and, i) => {
return (
<span
onClick={() => deleteTag(i, "and")}
key={i}
>
{and}
</span>
);
})}
</div>
)
}
When I click on the SPAN element, I want my "andArray.map" to render again.
The splice is working correctly, my array is ok... but the function does not re-render.
Thanks a lot.
.splice
mutates the array. React states have to be immutable. The immuatble way would be:
setAndState(and.filter((_, i2) => i2 !== i));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With