Search code examples
javascriptreactjsreact-nativecomponentssetstate

My state is not changing to call1 from call


I want to make a DynamicBarChart, but I am unable to update the state. Could you figure out why?

import React, { Component } from 'react';
import { DynamicBarChart } from 'react-dynamic-charts';
import 'react-dynamic-charts/dist/index.css';

class Dynamicchart extends Component {
  constructor(props) {
    super(props)

    this.state = {
      data: [{ "name": "Call", "values": [] }]
    }
  }

  componentDidMount = async () => {
    const mockData = [
      {
        id: 1,
        value: 10,
        label: "hey",
        color: "red"
      }
    ]
    const newwData = [{
      "name": "Call1",
      "values": mockData // Here i changed the values of the data
    }]

    this.setState({
      data: newwData // This method is unable to change the state.data component
    });

    // This still gives the value of data which is given in constructor 
    // Why has the value not changed?
    console.log(this.state.data) 
  }

  render() {
    return (
      <DynamicBarChart
        data={this.state.data}
      />
    );
  }
}

export default Dynamicchart

This code is showing "Call" in front-end, I want the value of "Call1". This means that the state did not change. Can you explain why this is happening?


Solution

  • Adding a random key to the DynamicBarChart component will solve the issue:

        return <DynamicBarChart key={Math.random()} data={this.state.data} />;
    

    I created a sandbox to demonstrate this with a fake delay in this Example with Simulated API Request.


    That being said, the comment of @Waheed is valid, regarding accessing this.state.data right after calling this.setState({...}) as the latter is async. If you want to see the data update, use the console.log in the render() block or as a callback of the setState like @Waheed mentioned in his reply.

    The reason why the component is not re-rendering is because you're mutating the state with new data. By setting a random key you're forcing the DynamicBarChart component re-rendering.