1

For some reason I can't seem to find an answer to this rather simple task I believe. My challenge is that I have a usestate array which holds multiple objects depending on the user input. It can have as many as the user chooses or none. For some reason I can't get it to work right.

What I mean is that whenever I set the state (for example: setFinal(final => [...final, value]);) in any way that I've been able to come up with so far it doesn't work properly. It works fine when the user adds on click a new object to the array but deleting them and particularly coming from 1 to 0 to 1 again causes the state to be invalid. What I mean is that the last one before going to 0 doesn't get deleted and when you start to add new objects from 0 again it has already one value in state.

So, what is the right way to set state so that it works correctly no matter if you're adding or deleting objects from the state?

Hopefully I've made myself clear enough for a solution to this. It should be fairly straightforward but I don't seem to get it right and googling doesn't seem to do the trick. Thanks in advance for anyone helping me.

EDIT:

Something for clarification:

example objects:

0: Object { id: 484, data: [] }
1: Object { id: 524, data: [] }
2: Object { id: 170, data: (3) […] }

What I've tried so far in setting state:

setFinal(final => [...final, value]);
setFinal(value);
setFinal(final => value);

I would need it to work no matter whether you add or delete, delete them all and add again, it should work in all of these conditions.

Adrian Mole
  • 30,672
  • 69
  • 32
  • 52

2 Answers2

0

Are you looking something like this? Live Demo

function App() {
  const [arr, setArr] = useState({
    numbers: [
      { id: 1, name: "Reactjs" },
      { id: 2, name: "Vuejs" },
      { id: 3, name: "Nodejs" }
    ]
  });

  const onclickHandler = event => {
    setArr({
      ...arr,
      numbers: [
        ...arr.numbers,
        {
          id: Math.floor(Math.random() * 100),
          name: `${Math.random()} technology`
        }
      ]
    });
  };
  const deleteIt = item => {
    let updated = arr.numbers.filter(a => a.id !== item.id);
    setArr({ numbers: updated });
  };

  return (
    <div className="App">
      <button onClick={onclickHandler} value="4">
        Add
      </button>
      <ul>
        {arr.numbers.map(a => (
          <li key={a.id}>
            <span>
              {a.id}-{a.name}
            </span>
            <button style={styles} onClick={() => deleteIt(a)}>
              X
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
const styles = {
  color: "white",
  backgroundColor: "red"
};
akhtarvahid
  • 6,733
  • 2
  • 14
  • 21
0

You can't delete element from array via setFinal(final => [...final, value]); If value is undefined then setFinal just ignore it. Please see: Delete item from state array in react

Alexander
  • 771
  • 3
  • 10