Last active
May 2, 2016 22:06
-
-
Save denisraslov/c145dbafcf4d15e7b56b29ac2fbc26f6 to your computer and use it in GitHub Desktop.
redux-thunk actions example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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