Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
React Hooks: state variable having wrong value in event handlers, not able to type in input

Below, i am rendering <App/> component with children as <Input/> component array. I added few inputs using "add new" button. I am able to add input text components. But, when i am typing value in text, it is not displaying. i am not able to modify object in state array since index is showing as "-1" in setData function. Due to this, value is not showing when we type in text box. Please let me know why state is [] when i am accessing in setData function.

    function Input(props)
    {
        return (
            <div>
                <label htmlFor='variable'>Name</label>
                <input id='variable'
                    type='text'
                    value={props.value}
                    onChange={(e) => props.setData(props.id, e.target.value)} />

            </div>
        )
    }
    function App()
    {
        let [state, setState] = React.useState([])
        let [inputs, setInputs] = React.useState([])
        let setData = ((id, value) =>
        {
            console.log(state); // prints []
            let index = state.findIndex(ele => ele.key === id);
            console.log(index); // prints -1
            if (!(index === -1))
            {
                setState(state =>
                {
                    state[idx]["value"] = value;
                })
            }
        })
        let handleAdd = () =>
        {
            let idx = `${new Date().getTime()}`
            let tempState = {
                "key": idx,
                "value": "",
            }
            setState(state => [...state, tempState])
            let input = <Input key={tempState.key}
                value={tempState.value}
                id={tempState.key}
                setData={setData} />
            setInputs(inputs => [...inputs, input])
        }
        return (
            <div>
                <button onClick={handleAdd}>add new</button>
                <div>
                    {inputs}
                </div>
            </div>
        )
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

When you create an Input component inside handleAdd, it creates a closure and as a result setData gets the state that existed when the component was created, missing the newly added state.

In general, creating components and saving them to state is not a good approach. Instead it's better to only save the data onto state and render the components based on it.

Here's one way to do this, note how much simpler the component and its logic are.

function App() {
  let [state, setState] = React.useState([]);

  let setData = (id, value) => {
    const newState = state.map((st) => {
      if (st.key === id) {
        st.value = value;
      }

      return st;
    });

    setState(newState);
  };

  const addInput = () => {
    const idx = `${new Date().getTime()}`;
    setState([...state, { key: idx, value: '' }]);
  };

  return (
    <div>
      <button onClick={addInput}>add new</button>
      <div>
        {state.map((st) => (
          <Input value={st.value} key={st.key} setData={setData} id={st.key} />
        ))}
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!