Search code examples
reactjscomponents

Can't perform a React state update on an unmounted component, using class component and component did mount


I have certain code as below:-

class BarChart extends Component {
  constructor(){
    super();
    this.state = {
      chartData:{}
    }
  }

  componentDidMount() {
    this.getChartData();
  }

  getChartData() {
    axios.get("http://localhost:5001/inventory/clusterscount").then(res => {
        const myresponse = res.data;
        console.log(myresponse)
        let countcluster = [];
        let listregion = [];
        for (const dataobj of myresponse){
            countcluster.push(parseInt(dataobj.clusterscount));
            listregion.push(dataobj.region);
        }
        console.log(countcluster)
        console.log(listregion)
        this.setState({
          chartData: {
            labels:listregion,
            datasets: [
              {
                label: "level of thiccness",
                data: countcluster,
                backgroundColor: ["rgba(75, 192, 192, 0.6)"],
                borderWidth: 4
              }
            ]
          }
        });
      });
    }

  render(){
        return (
            <div className="App">
              <h1>Dankmemes</h1>
              <div>
                <Line
                  data={this.state.chartData}
                  options={{
                    responsive: true,
                    title: { text: "THICCNESS SCALE", display: true },
                    scales: {
                      yAxes: [
                        {
                          ticks: {
                            autoSkip: true,
                            maxTicksLimit: 10,
                            beginAtZero: true
                          },
                          gridLines: {
                            display: false
                          }
                        }
                      ],
                      xAxes: [
                        {
                          gridLines: {
                            display: false
                          }
                        }
                      ]
                    }
                  }}
                />
              </div>
            </div>
          );
    
        }     
    }
export default BarChart;

Now while running it am getting the desired clusters and regions as below:-

0: {clusterscount: '2', region: 'test1'}
1: {clusterscount: '10', region: 'test2'}
2: {clusterscount: '8', region: 'test3'}
3: {clusterscount: '1', region: 'test4'}
4: {clusterscount: '8', region: 'test5'}
5: {clusterscount: '2', region: 'test6'}

I am able to get results for clustercount and listregion as well, but keep getting this error. I have tried multiple things but out of ideas.

But in logs am getting as below:- enter image description here

Can someone help me with this?


Solution

  • The react useEffect expects a cleanup function to cancel subscription and asynchronus tasks so we need to check if component is mounted or not there are couple of ways we can do it and react community have good solution for that.

    const LineChart = () =>{
        const [chartData,setChartData]= useState({});
        const [myresponse, setmyresponse] =useState([]);
      const isMountedRef = useRef(null);
        useEffect(() =>{
        isMountedRef.current = true;
            let countcluster = [];
            let listregion = [];
            axios.get("http://localhost:5001/inventory/clusterscount").
            then(res=>{
               if(isMountedRef.current){
       const myresponse= res.data;
                setmyresponse(myresponse)
                console.log(myresponse);
             for (const dataobj of myresponse){
                 countcluster.push(parseInt(dataobj.clusterscount));
                 listregion.push(dataobj.region);
             }
             setChartData({
                labels: listregion,
                datasets: [
                  {
                    label: "level of thiccness",
                    data: countcluster,
                    backgroundColor: ["rgba(75, 192, 192, 0.6)"],
                    borderWidth: 4
                  }
                ]
              });
         
            }
            
             
            })
        .catch(err=>{
            console.log(err);
        });
        return () => isMountedRef.current = false;
        },[])