1

I'm trying to get rid of elements in an array using pop() So i tried like this:

function Test() {


const [nu, setnu] = useState([]);
  const delet = () => {
    nu.pop();
  };
  return (
    <div>
      <button onClick={() => setnu([...nu, "add"])}></button>
      <button onClick={delet}>delete nu</button>
      <h1>
        {nu.map(d => (
          <>{d},</>
        ))}{" "}
      </h1>
      }

but for some reason elements didn't get disappeared until I click add button

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
KYUN
  • 185
  • 5

1 Answers1

5

You shouldn't mutate state as you do with nu.pop(). Instead, shallow copy the state and then update it. Here, you can use filter function as it will generate a new array:

  const delet = () => {
    setnu(nu => nu.filter((n,index) => index !== nu.length-1 /* or any other condition */));
  };

As @DrewReese suggested, a more efficient way:

  const delet = () => {
    setnu(nu => nu.slice(0,-1));
  };

If you want to use pop()

const delet = () => {
  const copyOfNu = [...nu]
  copyOfNu.pop()
  setnu(copyOfNu)
}

Both does the same thing, it modifies a copied version of the state variable. When you call the setState function, react knows the state variable has changed

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35
  • 1
    No problem, [this question](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js) might be worth reading :) – Sinan Yaman Aug 09 '21 at 07:52
  • 4
    `setnu(nu => nu.slice(0, -1));` to remove the last item (*well, rather copy all but the last element*) and return a new array. – Drew Reese Aug 09 '21 at 07:54
  • 1
    @DrewReese yet again, a better way. I will include it in the answer, and I thought slice was returning the sliced element. I guess mixed it with splice :D – Sinan Yaman Aug 09 '21 at 07:56
  • 1
    Yeah... ...slice ...splice ...who names these things? – Drew Reese Aug 09 '21 at 07:58