Using React and API calls, I separated the API fetch to a different class. The goal is to create an instance of the API class after that to call the "api_call()" method which fetches the data. The data is then stored in the instance object, and I would then take that data and change the React State based on whatever data that is.
However, an important part is awaiting for the fetch response, But I'm not sure where to implement it. Would you implement async await inside the methods in the API class? or would you implement async await from where you call the api_call method in the React class?
React Class
API obj is instantiated and the fetch process is called
class App extends Component {
constructor(props){
super(props);
this.state = {
}
}
componentDidMount(){
var RESTAPI = new API();
RESTAPI.api_call();
console.log(RESTAPI.infomation);
}
}
API Class
class API {
constructor(){
this.url = "https://restcountries.eu/rest/v2/all";
this.data = null;
this.information = null;
}
api_call(){
fetch(this.url)
.then((response) => response.json())
.then(function(data){
this.data = data;
this.api_sort();
}.bind(this))
}
api_sort(){
var infoObj = {
name: this.data[0].name
}
this.information = infoObj;
}
}