Fabio Russo
Fabio Russo

Reputation: 271

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.

Upvotes: 4

Views: 2062

Answers (2)

b0b
b0b

Reputation: 446

React state has to receive a change but as the array address stays the same nothing is re-rendered. In short: React State doesn't check deep.

I just created a new array from the old one. This way an address change is triggered. It is readable and it makes you be able to use functions of splice like inserting.

  and.splice(1, 0, newValueAtIndexOne);
  setAndState(Array.from(and));

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138437

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

  setAndState(and.filter((_, i2) => i2 !== i));

Upvotes: 6

Related Questions