I cannot understand, why when I try to start the function getTodosList inside the getDerivedStateFromProps the method - it always retrun to me the TypeError - Cannot read property 'getTodosList' of null. 
Also after I start use the getDerivedStateFromProps - my function does not start in componentDidMount too...
What is I'm doing wrong? (
import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';
class Chart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // some state...
    }
    getTodosList = (todos) => {
        console.log(todos);
        const all = [];
        const done = [];
        // some logic...
    }
    componentDidMount() {
        const { todos } = this.props.state.iteams;
        console.log('componentDidMount', todos);
        this.getTodosList(todos);
    }
    static getDerivedStateFromProps(nextProps, prevState) {
        const { todos } = nextProps.state.iteams;
        console.log(this.getTodosList, prevState.datasets, 'componentWillReceiveProps', todos);
        this.getTodosList(todos); // TypeError: Cannot read property 'getTodosList' of null
    }
getDerivedStateFromProps is a static property of the class (as indicated by the static keyword in front of it). This means it doesn't have access to any instance functions/properties. 
Declare your getTodosList as static as well (if it also doesn't use any instance properties) then call Chart.getTodosList(todos).
Edit:
If you call setState in getTodosList, you can change it to return the state object instead, then you can construct/update your state based on the returned object from your calling function.
Eg.
static getTodosList = todos => {
  ...
  return { someState: someData }; //instead of this.setState({ someState });
}
static getDerivedStateFromProps() {
  ...
  return Chart.getTodosList(todos);
}
You also don't need the componentDidMount if it's doing the same thing as getDerivedStateFromProps.  
getDerivedStateFromProps is a static method, it will not have the access of any instance property/method, means this will not be available inside that method.
Use componentDidUpdate to perform the operation you want on state/props change. 
You need to put the check between prevState/prevProps vs the new values.
componentDidUpdate(prevProps, prevState, snapshot) {
   // compare this.state and prevState or compare the props values 
   // and perform the operation
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With