-1

This is the following code

//inside constructor    

this.state = {            
        id: props.id,
        name: props.name,
        dataLoaded: false,
        data: require('../data/'+props.id+'.json')
    }

Will the data be available when the component was mounted? or it is async or synchronous?

Is it proper way to load data? Or any better solution available?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Mahesh
  • 1,503
  • 3
  • 22
  • 33
  • Have your tried to run this code? You got error or something? – Abdulhaq Shah Aug 26 '19 at 06:55
  • It is working as expected. I can make the componentDidMount as a async function and fetch the json. But don't know which one is the best way. – Mahesh Aug 26 '19 at 06:56
  • If you add `console.log(this.state.data)` immediately after this code, and it prints the correct data, then you can be sure that it's synchronous. – JJJ Aug 26 '19 at 07:02
  • 1
    I think you should go with it. Mostly people have used the fetch method but what is the need of fetch method if we can easily access the file like that. So you should go with it unless you get any problem :) – Abdulhaq Shah Aug 26 '19 at 07:02

1 Answers1

1

Two ways are visible for me. One is if you are only using the 'require' to import a data (static, maybe): I recommend you to checkout Webpack ... and this post. However, if your aim is to load data (dynamic, maybe), it is recommended to start the (maybe time taking) async request by overriding componentDidMount() method. It is not recommended to call any async methods in the constructor. Do the following...

// inside the constructor
this.state = {            
        id: props.id,
        name: props.name,
        dataLoaded: false,
        data: null
    }



componentDidMount () {
       // This will only be called once [safe place to start async requests]
       const data = require('../data/'+props.id+'.json');
       // when it had loaded the json, 
       this.setState({data});
}