Last active
August 31, 2017 19:31
-
-
Save andrerfneves/59b850322538d51085a3ae4481a93394 to your computer and use it in GitHub Desktop.
Typical API request for a React application using `redux-thunk` to handle asynchronous calls and trigger request, success, and error action creators.
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
// @flow | |
import { getPageData } from '../../../services/api'; | |
import { toggleAppStateLoading } from '../loading/toggle-app-state-loading'; | |
import { | |
FETCH_PAGE_DATA_ERROR, | |
FETCH_PAGE_DATA_REQUEST, | |
FETCH_PAGE_DATA_SUCCESS, | |
} from '../../../constants/action-names'; | |
/** | |
* @name - fetchPageDataError | |
* @description - action creator for error event on page data fetch | |
* @param {string} error - error message from server | |
*/ | |
const fetchPageDataError = (error: string) => ({ | |
type: FETCH_PAGE_DATA_ERROR, | |
payload: { | |
error, | |
}, | |
}); | |
/** | |
* @name - fetchPageDataRequest | |
* @description - action creator for request event on page data fetch | |
* @param {string} pagePath - path to page on server | |
*/ | |
const fetchPageDataRequest = (pagePath: string) => ({ | |
type: FETCH_PAGE_DATA_REQUEST, | |
payload: { | |
pagePath, | |
}, | |
}); | |
/** | |
* @name - fetchPageDataSuccess | |
* @description - action creator for success event on page data fetch | |
* @param {string} pagePath - path to page on server | |
* @param {object} pageData - data object returned from the server | |
*/ | |
const fetchPageDataSuccess = (pagePath: string, pageData: Object) => ({ | |
type: FETCH_PAGE_DATA_SUCCESS, | |
payload: { | |
pagePath, | |
pageData, | |
}, | |
}); | |
/** | |
* @name - fetchPageData | |
* @description - redux thunk for handling asynchronous calls to the api | |
* that will handle request, success, and error action calls asynchronously | |
* upon unknown completion time of request | |
* @param {string} pagePath - path for page on server | |
*/ | |
export const fetchPageData = (pagePath: string) => (dispatch, getState) => { | |
if (!pagePath) return; | |
dispatch(toggleAppStateLoading(true)); | |
dispatch(fetchPageDataRequest(pagePath)); | |
return getPageData(pagePath) | |
.then((responseData) => dispatch(fetchPageDataSuccess(pagePath, responseData))) | |
.then(() => dispatch(toggleAppStateLoading(false))) | |
.catch((err) => dispatch(fetchPageDataError(err))); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment