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?`
2
Answers
Your problem seems to be here:
modifyInp((prevState) => [{ ...prevState, ...input }]);
here
prevState
is 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 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:Or
inp
is an object andinput
too and you want to mergeinput
intoinp
:The above answer is correct and there’s another way of writing your function:
Explanation:
It takes an
event
as a parameter, typically from an input field in a web application. Inside the function, it extracts the value entered into the input field usingevent.target.value
and assigns it to a variable called value. It then calls a function namedmodifyInp
with value as an argument. This function is likely responsible for processing or updating the input value in some way. Overall,inputHandler
is designed to handle input events and pass the input value to a function for further manipulation.