Ashwani Panwar
Ashwani Panwar

Reputation: 4568

Why component is not re-rendering after deletion in react

Trying to delete element from list but its not re-rendering even I am using useEffect. my code is

    import React from "react";
import "./styles.css";
import { useEffect, useState } from "react";

const initialList = [
  {
    id: 'a',
    firstname: 'Robin',
    lastname: 'Wieruch',
    year: 1988,
  },
  {
    id: 'b',
    firstname: 'Dave',
    lastname: 'Davidds',
    year: 1990,
  },
  {
    id: 'c',
    firstname: 'ssh',
    lastname: 'asssss',
    year: 1990,
  },
  {
    id: 'd',
    firstname: 'Asdf',
    lastname: 'we32e',
    year: 1990,
  },
];

export default function App() {
  const [list, setList] = useState(initialList);
  useEffect(() => {
    console.log('useEffect has been called!');
    setList(list);   
  }, [list]);

  const handleRemove = (id,i) => {
    list.splice(i,1)
    setList(list);
  }
  return (
    <div className="App">
    <ul>
      {list.map((item,i) => (
        <li key={item.id}>
          <span>{item.firstname}</span>
          <span>{item.lastname}</span>
          <span>{item.year}</span>
          <button type="button" onClick={() => handleRemove(item.id,i)}>
            Remove
          </button>
        </li>
      ))}
    </ul>
    </div>
  );
}

Upvotes: 0

Views: 116

Answers (1)

Konstantin
Konstantin

Reputation: 1458

It's always a problem in react modifying the state directly and is generally considered an anti-pattern. You could just do something like:

const handleRemove = (id) => {
    const newArr = list.filter((el) => el.id !== id);
    setList(newArr);
  }

And you don't need any useEffect either, the function should handle the state change.

Upvotes: 1

Related Questions