Questions about react Asynchronous action

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())
        });


    }
}

the asynchronous action mode above encapsulates the code for initiating the request into action, that is to say, asynchronous action is only for the purpose of unifying the interface of dispatch?


this makes your components cleaner, separates this url request from presentation, and facilitates reuse and unit testing

Menu