Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda