here is the code that does not use asynchronous action
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onLoadSuccessHandle: (weather) => {
dispatch(loadSuccess(weather))
},
onLoadFailureHandle: () => {
dispatch(loadFailure())
}
}
}
componentDidMount() {
const cityCode = 101010100
const apiUrl = `/data/cityinfo/${cityCode}.html`;
fetch(apiUrl).then((response) => {
if (response.status !== 200) {
throw new Error("Fail to get response with status " + response.status);
}
response.json().then((responseJson) => {
this.props.onLoadSuccessHandle(responseJson.weatherinfo)
}).catch((error) => {
this.props.onLoadFailureHandle()
});
}).catch((error) => {
this.props.onLoadFailureHandle()
});
}
here is an asynchronous action
export const loadWeather = () => {
return (dispatch) => {
dispatch(loadStarted())
const cityCode = 101010100
const apiUrl = `/data/cityinfo/${cityCode}.html`
fetch(apiUrl).then((response) => {
if (response.status !== 200) {
throw new Error("Fail to get response with status " + response.status);
}
response.json().then((responseJson) => {
dispatch(loadSuccess(responseJson.weatherinfo))
}).catch((error) => {
dispatch(loadFailure())
});
}).catch((error) => {
dispatch(loadFailure())
});
}
}