reactjs – How to update the state element properly in react js?
Your problem seems to be here:
modifyInp((prevState) => [{ ...prevState, ...input }]);
here prevState
is in fact what you call inp
, it is supposed to be an array so if your intent is to append the input to inp your are not using the spread operator properly.
Here you are spreading prevstate into an object, then you spread input in the same object and put the result into the first element of an array and return it as the new inp
.
It doesn’t make sense.
either inp
is indeed an array and you should do this to append input to this array:
// if input is a single element:
modifyInp((prevState) => [...prevState, input ]);
// if input is itself an array and you want to append all of its elements:
modifyInp((prevState) => [...prevState, ...input ]);
Or inp
is an object and input
too and you want to merge input
into inp
:
modifyInp((prevState) => ({ ...prevState, ...input }));
Read more here: Source link