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

85
Visualizações
Child component value not updating after set state

I am attempting to update properties on a parent object via button clicks in the child components. After clicking the increment button neither of the child components get updated.

NOTE: id is purely to differentiate between propA and B for saving state

Also is there a nice way to deal updating object properties without having to do a switch statement

Minimum reproduction

import { useState } from "react";
import "./styles.css";

export default function App() {
  let [object, setObject] = useState({
    propertyA: 0,
    propertyB: 0
  });

  function handleClick(id) {
    switch (id) {
      case 1:
        setObject((prevState) => ({
          ...prevState,
          propertyA: prevState.propertyA + 1
        }));
        break;
      case 2:
        setObject((prevState) => ({
          ...prevState,
          propertyB: prevState.propertyB + 1
        }));
        break;
      default:
        console.log(id);
        break;
    }
  }

  return (
    <div className="App">
      <Child
        id="1"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />
      <Child
        id="2"
        title="property B"
        value={object.propertyB}
        handleClick={handleClick}
      />
    </div>
  );
}

function Child(props) {
  return (
    <div>
      {props.title} : {props.value}
      <button onClick={props.handleClick(props.id)}>Increment</button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

onClick={props.handleClick(props.id)} should be onClick={()=>props.handleClick(props.id)}, and for the avoiding switch you can set the id as the property name

 <Child
        id="propertyA"
        title="property A"
        value={object.propertyA}
        handleClick={handleClick}
      />

and then

function handleClick(id) {
  setObject((prevState) => ({
          ...prevState,
         [id]: prevState[id] + 1
        }))
}
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