Search code examples
reactjstypescriptreact-state-managementreact-lifecycle

Access updated state values of child from parent in react


I have one component 'Checkin', which further includes a child component 'CheckinGraph'. Checkin graph component has three states values which initialize to 0 but, on the ComponentDidMount life cycle, their values change from 0 to specific values. I want to access these state variables from the parent component.

Here is my code by which I access these state variables.

Child Component

class CheckinGraph extends React.PureComponent{
    constructor(props)
    {
        super(props)
        this.state={
         totalMaleCount:0,
         totalFemaleCount:0,
         totalUnspecifiedCount:0
      }
    }

//Callback function for parent

getCount=()=>
    {
        let { totalMaleCount, totalFemaleCount, totalUnspecifiedCount}=this.state;
        let arr=[totalCount,totalMaleCount,totalFemaleCount, totalUnspecifiedCount];
        return arr;
    }
   componentDidMount()
    {
     this.setState({totalMaleCount:res.data.maleListCount}); //data is coming from API
     this.setState({totalFemaleCount:res.data.femaleListCount});
     this.setState({totalUnspecifiedCount:res.data.notSpecified});

     }
}

Parent component


class CheckIn extends React.Component{
    constructor(props)
    {
     this.state={}
     this.graph=React.createRef();
    }

 componentDidMount()
    {
        let total=this.graph.current.getCount();
        console.log(total);

    }
render()
{
return(
<div>
<CheckinGraph ref={this.graph} />
</div>
)
}
}

Now the problem is, I able to access values from child to parent, but it is the initial values, not the updated values. Any idea what I am doing wrong?


Solution

  • Two approaches:

    1. Use Redux to manage state and then dispatch an action from CHild Component

    2. Pass onChange Function to Child Component and whenever value updated to call the function from Child Component. The onChange Function is where you will have access to updated value and then you can do whatever you want to do in Parent.