How can I set a new array without an object that is selected with react.js, splice?

163 Views Asked by At

How can I set a new array without an object that is selected?

  const [chips, setChips] = useState([
    { type: "keyword", text: "000" },
    { type: "keyword", text: "111" },
    { type: "keyword", text: "222" }
  ])

  const handleDelete = idx => {
    const newChips = chips.splice(idx, 1);
    setChips(newChips);
  };

   const renderChips = useMemo(
    () =>
      chips.map(({text}, idx) => (
        <Chip
          key={text}
          onDelete={() => handleDelete(idx)}
        />
      )),
    [chips, handleDelete],
  );

Let's say I clicked chips[1], I'd like to remove chips[1] from the chips array and set a new array without chips[1].

So the new array will look like this.

([
    { type: "keyword", text: "000" },
    { type: "keyword", text: "222" }
  ]

How can I do it?

3

There are 3 best solutions below

0
Irfanullah Jan On BEST ANSWER

It is important to deep copy the chips array correctly in this case, otherwise the objects inside chips array will be copied by reference. So in handleDelete function, you can try:

const handleDelete = (idx) => {
  const newChips = chips.map((chip) => ({...chip})); // deep copy
  newChips.splice(idx, 1);
  setChips(newChips);
};

UPDATE: Also tried the following, which works too, so a superficial copy will work too, and a full nested copy isn't actually needed:

const handleDelete = (idx) => {
  const newChips = [...chips]; // superficial copy
  newChips.splice(idx, 1);
  setChips(newChips);
};

Sandbox: https://codesandbox.io/s/ecstatic-haslett-pyh4im?file=/src/App.js:0-661

0
Ziyed On

You using splice wrongfully here, I'll invite you to check here the doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice This modify the original array and doesn't return anything, which means in your case newChips = []

Instead you could do

const newChips = chips;
newChips.splice(idx, 1);
setChips(newChips);

On the first line, when assigning chips, you could do a hard copy here, but I think you can get away without

1
Behemoth On

Array#splice() does not return a modified array but instead modifies the current one. What you need to do is adapt your handleDelete function as follows:

const handleDelete = idx => {
  setChips([...chips].splice(idx, 1));
};