Last active
May 27, 2017 00:47
-
-
Save chrisgervang/14dabb53458058c4f2e0a0ef935eb1f6 to your computer and use it in GitHub Desktop.
Redux Thunk Helpers
This file contains hidden or 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 * as Redux from 'redux' | |
import { ThunkAction } from 'redux-thunk' | |
import { Store } from './store' | |
export type Status = 'pending' | 'success' | 'fail' | |
export interface Request { | |
status: Status | |
error?: string | |
} | |
export interface LoadEndpoint<T> extends Redux.Action { | |
type: string | |
request: Request | |
data: T | |
} | |
type Creator = (dispatch: Redux.Dispatch<Store>, getState: () => Store) => void | |
export function thunk (creator: Creator): ThunkAction<void, Store, null> { | |
return (dispatch, getState) => { | |
/** define and then call an async function */ | |
(async (dispatch, getState) => { | |
await creator(dispatch, getState) | |
})(dispatch, getState).catch(error => { | |
console.error(error) | |
}) | |
} | |
} | |
export function loadEndpoint<T> (endpoint: Promise<T>, type: string, fallbackData: any) { | |
return thunk(async (dispatch, getState) => { | |
dispatch<LoadEndpoint<T>>({ type, request: { status: "pending" }, data: fallbackData}) | |
await endpoint.then( data => { | |
dispatch<LoadEndpoint<T>>({ type, request: {status: "success"}, data }) | |
}, why => dispatch<LoadEndpoint<T>>({type, request: { status: "fail", error: why}, data: fallbackData})) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment