I am very new with React and I am trying to call the data from server with fetch api.
If I want to make a helper class to get the data like this one
import { Promise } from 'es6-promise';
import fetch from 'isomorphic-fetch';
let responseData = response => {
return response;
};
let getData = (dataURL, headers) => {
let result = {
data: [],
message: ''
};
if (dataURL === null || dataURL === undefined || dataURL === '') {
result.message = 'URL is not correct';
responseData(result);
}
fetch(dataURL, headers)
.then(response =>{
if (response.ok) {
response.json().then(data => {
result.data = data;
result.message = response.statusText;
responseData(result);
});
}else{
result.message = 'Network response was not ok.';
responseData(result);
}
})
.catch(err => console.log(err));
};
exports.responseData = responseData;
exports.getData = getData;
and whenever the data is available, I will ask the React render the view, during the waiting time, it will show a loading icon.
I put the call inside componentDidMout but by the time it is executed, the result is always undefined.
componentDidMount() {
var self = this;
let result = util.getData('http://localhost:3001/menus');
const { dispatch } = this.props;
// dispatch(menuActions.fetchMenusIfNeeded());
if (result !== null && result !== undefined) {
if (this.isMounted()) {
this.setState({
items: result.data.results
});
}
}
}
In Angular, whenever the data is available, it will be updated accordingly but I really don't understand how to do it in React.
EDIT 1: Update the helper class:
import { Promise } from 'es6-promise';
import fetch from 'isomorphic-fetch';
let getData = (dataURL, headers) => {
return fetch(dataURL, headers);
};
exports.getData = getData;
It will always return a Promise so I can chain handler for data in other components. The only problem that I need to handle the message return by reading Response object in my components.
In React component:
componentWillMount() {
util.getData('http://localhost:3001/menus')
.then(response =>{
if (response.ok) {
response.json().then(data => {
console.log(data);
this.setState({
items: data.result
});
});
}
})
.catch(err => console.log(err));
}
But whenever it received the data, the render() function already finished, should I force it to update again?
getDatafunction but even if you did returnresult, this is async so you won't seeresultincomponentDidMount.Promise, how should I inform React to update therender()functions.