Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function render after splice and setState()

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.

like image 572
Fabio Russo Avatar asked Mar 04 '23 01:03

Fabio Russo


1 Answers

.splice mutates the array. React states have to be immutable. The immuatble way would be:

  setAndState(and.filter((_, i2) => i2 !== i));
like image 123
Jonas Wilms Avatar answered Mar 11 '23 04:03

Jonas Wilms