Skip to content

Instantly share code, notes, and snippets.

@denisraslov
Last active May 2, 2016 22:06
Show Gist options
  • Save denisraslov/c145dbafcf4d15e7b56b29ac2fbc26f6 to your computer and use it in GitHub Desktop.
Save denisraslov/c145dbafcf4d15e7b56b29ac2fbc26f6 to your computer and use it in GitHub Desktop.
redux-thunk actions example
import request from 'axios';
// Let's assume we need to get the user data through API.
// We create the action function that takes the user id
// and make the async request.
export function getUser(id) {
// We have access to the Dispather to dispath
// actions inside of the action function.
return (dispatch) => {
request
.get(API_URL + '/users/' + id)
.then(function(req) {
// We dispatch the success action
// function when the request completes.
dispatch(setUser(req.data));
})
.catch(function(req) {
// We dispatch the error action function
// when the request ends with an error.
dispatch(setUserError(id));
});
};
}
//This is two usual sync action functions.
export function setUser(data) {
return {type: 'SET_USER', data};
}
export function setUserError(id) {
return {type: 'SET_USER_ERROR', id};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment