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

96
Visualizações
ReactJS while passing function from parent to child and accessing parent state not returning completely

I was trying to access Parent state when a function is called from Child component, for that created a function in Parent component and passed it to Child, issue is I am not able to access the state completely. for example on button click I add a new input field and a delete button, suppose I added 10 input fields, and added all of them in state array, but when i click delete button of second input field, the count I get from state is 1, similar if I click 5th delete button i get count as 4 and it only show me 4 items in state, but it has 10 items Here is an example link https://codesandbox.io/s/add-react-component-onclick-forked-t2i0ll?file=/src/index.js:0-869

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Input = ({ deleteRow, position }) => {
  const handleDelete = () => deleteRow(position);
  return (
    <>
      <input placeholder="Your input here" />
      <button onClick={handleDelete}>Delete</button>
    </>
  );
};

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onDeleteRow = (position) => {
    console.log("inputCount", inputList);
  };
  const onAddBtnClick = (event) => {
    setInputList(
      inputList.concat(
        <Input
          key={inputList.length}
          position={inputList.length}
          deleteRow={onDeleteRow}
        />
      )
    );
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList}
    </div>
  );
};

ReactDOM.render(<Form />, document.getElementById("form"));
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

It's called a stale closure.

You can avoid that by not storing react elements inside the state.

Example:

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onDeleteRow = (position) => {
    console.log("inputCount", inputList);
  };
  const onAddBtnClick = (event) => {
    setInputList([...inputList, inputList.length])
    );
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList.map(item => (
        <Input
          key={item}
          position={item}
          deleteRow={onDeleteRow}
        />
      )}
    </div>
  );
};
about 4 years ago · Santiago Trujillo 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