Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
}

>Solution :

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
        }))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading