0

I have a UserLists component where the user types into an input and adds the value onto the bottom of the screen.

The input value is added into the whitelist state. The state is then mapped and creates more inputs where the user can decide to delete said input or edit it.

I am having trouble deleting the inputs. I thought I could delete each input individually by splicing the state, but my implementation of the deleteItem deletes multiple inputs when any single one of them is clicked.

I also cannot edit any of the inputs because their value is set by my addItem function.

import React, { useEffect, useState } from "react";

export const UserLists = () => {
  const [whitelist, setWhiteList] = useState([]);
  const addItem = () => {
    let newValue = document.getElementById("whiteList").value;
    setWhiteList([...whitelist, newValue]);
  };
  useEffect(() => {
    console.log(whitelist, "item changed");
  }, [whitelist]);

  const deleteItem = (index) => {
    let test = whitelist.splice(index, 1);
    setWhiteList(test);
    console.log("index:", index);
  };
  const editItem = () => {};
  return (
    <div>
      <h2>WhiteList</h2>
      <input id="whiteList" type="text" />
      <button onClick={addItem}>Add</button>
      {whitelist.map((item, index) => {
        return (
          <div>
            <input type="text" value={item} onChange={editItem} />
            <button onClick={() => deleteItem(index)}>Delete</button>
            <p>{index}</p>
          </div>
        );
      })}
    </div>
  );
};

How can I revise my code to successfully individually delete and edit inputs? My codesandbox

1
  • Always check the docs first. Array#splice changes the array in place and returns the deleted items. Commented Dec 8, 2020 at 11:38

2 Answers 2

5

You need to change your editItem and deleteItem functions in order to make your edit and delete functionality work properly. Here's a code sandbox link to the solution to your problem:

https://codesandbox.io/s/whitelist-forked-y51w8

Sign up to request clarification or add additional context in comments.

Comments

1

Don't do:

let test = whitelist.slice(index, 1);
setWhiteList(test);

Do this instead:

whitelist.splice(index, 1);
setWhiteList([...whitelist]);

2 Comments

Thanks, that solves a big part of the delete functionality, although I need to edit it to correctly delete repeated input values. Could you explain what I was doing wrong before?
slice(index, 1) doesn't make sense, please review the documentation of this method. For index === 5 the return value will be [], removing the whole whitelist array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.