Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda