Home > Back-end >  Child component value not updating after set state
Child component value not updating after set state

Time:02-11

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

CodePudding user response:

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
        }))
}
  • Related