Search code examples
reactjscallbacksetstatereact-propsreact-functional-component

React : Callback value received in parent not passing the latest value in another child as prop | Function component


I am using function component:

I have 1 Parent and 2 child components.

Child 1 passing data to parent via call back. In parent the callback values are received and using setState it is assigning to a variable, and sent to child 2 correctly.

However when child 1 does any change and passes data to parent via callback, Parent is not passing the latest value in another child component as prop. Still showing old values.

Pictorial Illustration:

enter image description here

Sample Code :

const ContainerComponent = (props) => {
    let [selectedCenterId, setSelectedCenterId] = useState("");

    const callbackFromServiceDetails = (centerId) => {
        setSelectedCenterId((selectedCenterId = centerId));
        console.log("Inside parent callback");
        console.log(selectedCenterId);
    };

  return (  
      <>
        <ChildComponent1 activeTab={activeTab} parentCallback={callbackFromServiceDetails}></ChildComponent1>
        {
            selectedCenterId !== "" ?
            <ChildComponent2 activeTab={activeTab} selectedCenterId={selectedCenterId}></ChildComponent2>
            :
            <></>
        }
      </>
   );
};

export default ContainerComponent;


========================================================================

const ChildComponent1 = ({centersNLocations, actions, ...props}) => {

    const nextButtonClick = e => {
        e.preventDefault();
        props.parentCallback(selectedCenter);
      };

    return (
        <>
        ...
        </>
    );
};



ChildComponent1.propTypes = {
  ...
};

function mapStateToProps(state) {
  return {
    ...
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      ...
    }
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ChildComponent1);



=====================================

const ChildComponent2 = (props) => {
    let [centerId, setCenterId] = useState(props.selectedCenterId);
    console.log(centerId);

    return (
        <>
        ...
        </>
    );
};

export default ChildComponent2;

Any ideas what could cause such issue?


Solution

  • I believe that issue is in the parent component code as you change the reference from useState to the value itself. It line setSelectedCenterId((selectedCenterId = centerId)); you should not use equal operator so your function should looks like:

      const callbackFromServiceDetails = (centerId) => {
            setSelectedCenterId(centerId);
            console.log("Inside parent callback");
            console.log(selectedCenterId);
        };
    

    Tip for future: Use const instead of let if you want to keep reference not changed.