Jerald
Jerald

Reputation: 4048

Recommended way to do asynchronous actions in redux in angular 2

I use ng-redux module in angular 2 and I don't know what is the better way to do asynchronous actions. For example I need to fetch some data from server. I can do it using async action creator redux-thunk middleware: I will create an action that returns a function:

export function fetchData() {
    return function (dispatch) {
        dispatch({
            type: 'FETCH_DATA_REQUEST'
        });
        return fetch(url)
            .then(response => response.json())
            .then(json => dispatch({type: 'FETCH_DATA_SUCCESS', data: json}))
            .catch(error => dispatch({type: 'FETCH_DATA_ERROR', error: error
        }
    }
}
dispatch(fetchData());

Or I can do the HTTP request in controller and I will manually execute dispatch method:

dispatch({
    type: 'FETCH_DATA_REQUEST'
});
http(url).then(data => {
     dispatch({
        type: 'FETCH_DATA_SUCCESS',
        data: json
    });
}).catch(error => {
    dispatch({
        type: 'FETCH_DATA_ERROR',
        error: error
    });
});

Which method is recommended? I think that the second method is easier, but why then redux-thunk middleware exists.

Upvotes: 3

Views: 1208

Answers (1)

U r s u s
U r s u s

Reputation: 6968

Definitely the first method is what is recommended, especially if you're using a middleware library.

Only thing to remember is to dispatch your action inside the ComponentDidMount React lifecycle method.

Upvotes: 1

Related Questions