Home > Software design >  Modifying Hook setState for an Array in React using Splice
Modifying Hook setState for an Array in React using Splice

Time:08-30

I'm trying to splice an array hook State, so I can remove items from my list. I know you're not supposed to modify any hook states directly, so I made a copy into array2 before settting it, but it's removing all items below the one I click, instead of just the one I click. Any ideas?

export default function Shopping() {
  const [item, setItem] = useState('Default');
  const [list, setList] = useState([]);
  const [array, setArray] = useState([]);

  let array2 = [];
  const name = ({ target }) => setItem(target.value);

  const remove = ({ target }) => {
    for (let x = 0; x <= array.length; x  ) {
      if (array[x] === target.value) {
        array2 = list;
        array2 = array2.splice(x, 1);
      }
      setList([...list, array2]);
    }
  };

  const create = () => {
    if (item !== 'Default' && document.getElementById('box').value !== '') {
      let value = document.getElementById('box').value;

      setArray([...array, value]);

      setList([
        ...list,
        <div>
          <p>
            {' '}
            {item} &nbsp;&nbsp;&nbsp;&nbsp; Qty: 1<button> </button>
            <button>-</button>
            <button
              value={document.getElementById('box').value}
              onClick={remove}
            >
              x
            </button>
          </p>
        </div>,
      ]);
    } else {
      alert('Please enter an Item');
    }

    document.getElementById('box').value = '';
    setItem('Default');
  };

  const clear = () => setList([]);

  return (
    <div>
      <input type='textbox' id='box' onChange={name} />
      <input type='button' value='Add' onClick={create} />
      <input type='button' value='Clear' onClick={clear} />

      {list}
    </div>
  );
}

CodePudding user response:

You should just store the strings in the list array and display the elements using a map function:

export default function Shopping() {
  const [item, setItem] = useState('Default');
  const [list, setList] = useState([]);

  const name = ({ target }) => setItem(target.value);

  const remove = (index) => {
    const filteredList = [...list].splice(index, 1);
    setList(filteredList);
  };

  const create = () => {
    if (item !== 'Default' && item !== '') {
      setList([...list, item]);
    } else {
      alert('Please enter an Item');
    }

    setItem('Default');
  };

  const clear = () => setList([]);

  return (
    <div>
      <input type='textbox' id='box' onChange={name} />
      <input type='button' value='Add' onClick={() => create()} />
      <input type='button' value='Clear' onClick={() => clear()} />

      {list.map((it, index) => {
        return (
          <div key={index}>
            <p>
              {' '}
              {it} &nbsp;&nbsp;&nbsp;&nbsp; Qty: 1<button> </button>
              <button>-</button>
              <button value={it} onClick={() => remove(index)}>
                x
              </button>
            </p>
          </div>
        );
      })}
    </div>
  );
}
```

CodePudding user response:

Just Update the code in remove function because array2 = list also copies the reference of list array so when you update the array2 it also update the list array.so replace the remove function code with given code below .

if ((array[x])===target.value){
array2 = list.map(item=>item)
array2 = array2.splice(x,1)
}
  • Related