skip to Main Content
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


  1. 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 }));
    
    Login or Signup to reply.
  2. The above answer is correct and there’s another way of writing your function:

    const inputHandler = (event) => {
       //This is what I like to do most of the times.
       
       const value = event.target.value;
       modifyInp(value);
    };
    

    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 using event.target.value and assigns it to a variable called value. It then calls a function named modifyInp 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search