3
votes

I just switched out this.setState to use mobx observable, because I have multiple GET requests that fetch data. This prevents the PieChart from being re-rendered every time this.setState is called.

However, now the child component does not ever get re-rendered and stays with the initial placeholder mobxState. How can I get the PieChart child component to re-render when the data for it comes in from the API.

class Device extends React.Component {
  mobxState = {
    customOptions: [],
    rowData: []
  };

  //mount data
  componentDidMount() {
    //call the data loader
    this.fetchData();
  }

  fetchData = () => {
    axios
      .get("/custom_options.json")
      .then(response => {
        this.mobxState.customOptions = response.data.custom_options;
      })
      .then(
        //data for PieChart, need this portion to render the PieChart
        axios.get("/devices.json").then(response => {
          this.mobxState.rowData = response;
        })
      );
  };

  render() {
    return <PieChart data={this.mobxState.rowData} />;
  }
}

decorate(Device, {
  mobxState: observable
});

export default Device;
1

1 Answers

2
votes

You need to make sure your Device component is an observer, and if you are using a MobX version below 5 you have to slice() or peek() the array in the render method.

import { observer } from "mobx-react";

class Device extends React.Component {
  // ...

  render() {
    return <PieChart data={this.mobxState.rowData.slice()} />;
  }
}

decorate(Device, {
  mobxState: observable
});

export default observer(Device);