import React, { useState } from "react";
import Form from "./child/form.js";
import Details from "./child/details.js";
function App() {
const [inp, modifyInp] = useState([]);
const inputHandler = (input) => {
modifyInp((prevState) => [{ ...prevState, ...input }]);
};
console.log(inp);
return (
<div>
<Form inpHandler={inputHandler} />
<Details inputt={inp} />
</div>
);
}
export default App;
I am trying to update state of inp here, but it is not updating properly and insted the value is being replaced. Can anyone help me with this?`
Your problem seems to be here:
modifyInp((prevState) => [{ ...prevState, ...input }]);hereprevStateis in fact what you callinp, it is supposed to be an array so if your intent is to append the input to inp your are not using the spread syntax 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
inpis indeed an array and you should do this to append input to this array:Or
inpis an object andinputtoo and you want to mergeinputintoinp: