0

I want to fetch the value of the variable 'r2score' from flask. The value is fetched successfully. I even wote a console.log(r2score) statement to see if the fetching works. Here's the problem. Initially it logged a value of 0.1, which is its initial state. then in the next line of the console it logged a value of 0.26, which the value that was fetched from flask. So atleast the fetching was successful. However, the plot that is being drawn, is drawn with a value of 0.1(it's initial state) and not 0.26(it's fetched value).

My Code:

import ReactDOM from "react-dom";
import React from "react";

import { Liquid } from "@antv/g2plot";
import ReactG2Plot from "react-g2plot";

class R2ScorePlot extends React.Component {
  constructor(props) {
    super(props);
    this.state = { r2score: 0.1 };

  }

  componentDidMount() {
  fetch(`/fetch_regressionmodel`)
      .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error("Something went wrong ...");
        }
      })
      .then(info =>
        this.setState({
          r2score: info.R2score
        })
      ).then(    this.forceUpdate()      )
      .catch(error => this.setState({ error }));
  }
  shouldComponentUpdate() {
    return true;
  }
  render() {
    const { r2score } = this.state;
    console.log(r2score);

    const config = {
      title: {
        visible: false,
        text: ""
      },
      description: {
        visible: false,
        text: ""
      },
      min: 0,
      max: 1,
      value: r2score,
      statistic: {
        formatter: value => ((1 * value) / 1).toFixed(1)
      }
    };
    return (
      <div>


        <ReactG2Plot Ctor={Liquid} config={config} />
      </div>
    );
  }
}
export default R2ScorePlot;

Console Image

React Dev Tools

smit shah
  • 19
  • 4
  • You should not perform api calls in `constructor`, move fetch function in your `componentDidMount`. – Gulam Hussain Feb 28 '20 at 05:39
  • I originally did place it in componentDidMount, However the issue was still the same. Hence, I though of placing it in constructor, just to see if it changes anything. @hussain.codes – smit shah Feb 28 '20 at 05:45
  • i don't see anything "wrong" other than calling api in `constructor`. if console in `render` is printing updated state value, then i think you should check `ReactG2Plot` component. – Gulam Hussain Feb 28 '20 at 05:51
  • If your state changes successfully then the component will render surely with new values. But the main issue is that this will run only once when component is initialized for the first time (or first render) – Deepankar Singh Feb 28 '20 at 06:14
  • @DeepankarSingh I guess the state is changing. Otherwise I wouldn't have got the updated value in the console. Can you please suggest any steps, according to you, that might solve this? – smit shah Feb 28 '20 at 06:18
  • Don't guess dear @smitshah be sure, I already told you that if state would be changing then your component will surely re-render with new values – Deepankar Singh Feb 28 '20 at 06:23
  • And infact after using your code in sandbox, it clearly shows that your state is not updating console.log gives 0.1 – Deepankar Singh Feb 28 '20 at 06:35
  • This thing will surely work inside componentDidMount, first of all check request you are sending in fetch and what response it give by consoling – Deepankar Singh Feb 28 '20 at 06:45
  • @DeepankarSingh Have included the console snapshot in the question. The state is being updated. Please have a look, if you have some time. – smit shah Feb 28 '20 at 07:14
  • @smitshah I've already told you and this is the last time I'm telling you that on state change component re-renders with new value. First of all remove all 36 errors which are coming. I've lot of time to help others that's why I tried running your code on sandbox. – Deepankar Singh Feb 28 '20 at 07:21
  • For any other developers who might want to help me. Have included the React Dev tools snapshot in the question. The state is being updated as 0.26 after fetching. But the plot is using the initial state value of 0.10 only. Please have a look at the React Dev tools snapshot. – smit shah Feb 28 '20 at 07:29
  • I guess this is a similar issue to what I am facing currently https://stackoverflow.com/questions/25937369/react-component-not-re-rendering-on-state-change . Can anyone please point out what changes, I have to make exactly, referring the link – smit shah Feb 28 '20 at 08:09

1 Answers1

1

Have solved the issue. The solution was to wrap the graph component in a

<div key={r2score}>...</div>

So that the graph will rebuild whenever, the key changes.

My code:

import ReactDOM from "react-dom";
import React from "react";

import { Liquid } from "@antv/g2plot";
import ReactG2Plot from "react-g2plot";

class R2ScorePlot extends React.Component {
  constructor(props) {
    super(props);
    this.state = { r2score: 0.1 };

  }

  componentDidMount() {
    fetch(`/fetch_regressionmodel`)
      .then(response => {
        if (response.ok) {
          this.setState({ spinloading: false });
          return response.json();
        } else {
          throw new Error("Something went wrong ...");
        }
      })
      .then(info =>
        this.setState({
          r2score: info.Explained_Variance_score
        })
      ).catch(error => this.setState({ error }));
  }
  shouldComponentUpdate() {
    return true;
  }
  render() {
    const { r2score } = this.state;
    console.log(r2score);

    const config = {
      title: {
        visible: false,
        text: ""
      },
      description: {
        visible: false,
        text: ""
      },
      min: 0,
      max: 1,
      value: r2score,
      statistic: {
        formatter: value => ((1 * value) / 1).toFixed(1)
      }
    };
    return (
      <div key={r2score}>
        <ReactG2Plot Ctor={Liquid} config={config} />
        </div>
    );
  }
}
export default R2ScorePlot;
smit shah
  • 19
  • 4