score:2

Accepted answer

is there any reason not to use array.prototype.filter() just like you've done in your class component? this seems more readable and ensures you avoid mutating state directly in fewer steps.

here is what that would look like in your handledelete function in functioncomponent:

const handledelete = (id) => {
  setlist(list.filter((row) => (
    row.id !== id
  )));
};

score:0

you have to review your usage of the splice array prototype.

copy.splice(id, 1);

splice need to be passed as first argument an index and at second argument a delete count as such:

splice(start, deletecount)

and you are passing an id to it. actually in your case you are passing undefined as you're calling the function without argument. i guess you could use the index of the map function to make it work:

    {list.map(({ id }, index) => (
      <row key={id} id={id} onclick={() => handledelete(index)}>
        {id}
      </row>
    ))}

in your case you were passing undefined as id and 1 as the deletecount so it was always deleting the first item.

score:0

in the functional component, you did not pass the id!

const functionalcomponent = () => {
const [list, setlist] = usestate([{ id: uuidv4() }, { id: uuidv4() }]);

const handledelete = (id) => {
// get all object except the id
const newrows = list.filter((i) => i.id !== id);
setlist(newrows);
};

 const handleadd = () => {
   setlist([...list, { id: uuidv4() }]);
 };

 return (
    <>
    <ul>
    {list.map(({ id }) => (
      <row key={id} id={id} onclick={() => handledelete(id)}>
        {id}
      </row>
    ))}
  </ul>
  <button onclick={handleadd}>add</button>
  </>
 );
 };

score:1

in your functionalcomponent you need to give index of the entry to splice method. try like below.

  const handledelete = (id) => {
    const copy = list.slice();
    // find the index
    const index = copy.findindex(({ id: id }) => id === id);
    // do the deletiong using that index
    copy.splice(index, 1);
    setlist(copy);
  };

edit nifty-shannon-cv0k2u


Related Query

More Query from same tag