0
votes

I have managed to fetch data from an API successfully. Data transformation of JSON format works too, but i'm having trouble integrating it to "componentDidMount" to set state with a transformed JSON format. I'm getting an undefined state when i console.log(this.state.races).

I'm also getting this error message:

Can't call setState (or forceUpdate) on an unmounted component.

class Races extends Component {

    constructor(props) {
        super(props);
        this.state = {
          races: []};
        this.processResults = this.processResults.bind(this);  
    }

    componentDidMount(){
      fetch(RACE_SERVICE_URL) 
        .then(results => results.json()) 
        .then(this.processResults)
    }

    processResults(data) {

      const raceId_arr = data.map(d => d.raceId);
      const season_arr = data.map(d => d.season);
      const raceName_arr = data.map(d => d.raceName);
      const url_arr = data.map(d => d.url);
      const data_mapped = {'raceId': raceId_arr, 'season': season_arr, 'raceName': raceName_arr, 'url': url_arr};

      this.setState({races:data_mapped});
      console.log(data_mapped);
      console.log(this.state.races);
    }


    render() {
        const title = 'Race Tracks';

        return (
          <div>
            <h2>{title}</h2>
            <RacesViz data= {this.state.races.raceId} />
          </div>

        );
    }

}

export default Races;

I have also tried:

.then(data => this.processResults(data))

What console.log(data_mapped) prints:

{raceId:[1, 2, 3]
raceName:["AGP", "BGP", "CGP"]
season: [2018, 2018, 2018]
url: ["http://en.wikipedia.org/wiki/AGP", "http://en.wikipedia.org/wiki/BGP", "http://en.wikipedia.org/wiki/CGP"]}
2
Are you calling processData in your render method or in your child components ? - semuzaboi

2 Answers

1
votes

setState is async so you can't get immediate result with console.log like you did. Use a callback function instead:

this.setState({races:data_mapped}, () => console.log(this.state.races));

Or you can console.log your state in your render method.

1
votes

Quote from official docs:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

Important!

This makes reading this.state right after calling setState() a potential pitfall.

So you will not get state immediately after setState. You have 2 ways to solve it.

1) You should check in componentDidUpdate hook.

componentDidUpdate(prevProps, prevState) {
    console.log(this.state.races);//your data updated here.
}

You can see here to use properly.

2) Or you use callback in setState like this setState(updater, callback):

this.setState({races:data_mapped}, () => {
    console.log(this.state.races)//your data updated here.
})