Created
November 12, 2016 14:45
-
-
Save guillaume86/0ae9a67c011ddd2ff10e988a7c44ab8d to your computer and use it in GitHub Desktop.
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
namespace Redux { | |
export interface Action<TType extends string, TPayload> { | |
type: TType; | |
payload: TPayload; | |
} | |
export interface Thunk<TAction, TResult> { | |
(dispatch: Dispatch<TAction>, getState: () => any): TResult; | |
} | |
export interface Dispatch<TAction> { | |
(action: TAction): void; | |
<TResult>(thunk: Thunk<TAction, TResult>): TResult; | |
} | |
} | |
namespace Example { | |
namespace ActionTypes { | |
export type REQUEST = 'REQUEST'; | |
export type COMPLETE = 'COMPLETE'; | |
export type FAILURE = 'FAILURE'; | |
export const REQUEST: REQUEST = 'REQUEST'; | |
export const COMPLETE: COMPLETE = 'COMPLETE'; | |
export const FAILURE: FAILURE = 'FAILURE'; | |
} | |
type TypedAction = | |
Redux.Action<ActionTypes.REQUEST, { value: string }> | |
| Redux.Action<ActionTypes.COMPLETE, { result: any }> | |
| Redux.Action<ActionTypes.FAILURE, { error: any }> | |
; | |
namespace ActionCreators { | |
export function request(value: string): Thunk<TypedAction, Promise<string>> { | |
return (dispatch) => { | |
dispatch({ | |
type: ActionTypes.REQUEST, | |
payload: { value, bla: '' }, | |
}); | |
const promise = new Promise((resolve) => { | |
resolve('OK: ' + value); | |
}); | |
promise.then( | |
result => dispatch(requestComplete(result)), | |
error => dispatch(requestFailure(error)) | |
); | |
return promise; | |
}; | |
} | |
export function requestComplete(result: any): TypedAction { | |
return { | |
type: ActionTypes.COMPLETE, | |
payload: { result }, | |
}; | |
} | |
export function requestFailure(error: any): TypedAction { | |
return { | |
type: ActionTypes.FAILURE, | |
payload: { error }, | |
}; | |
} | |
export function reducer(state, action: TypedAction) { | |
switch (action.type) { | |
case ActionTypes.REQUEST: { | |
const { payload } = action; | |
return Object.assign({}, state, { value: payload.value }); | |
} | |
case ActionTypes.COMPLETE: { | |
const { payload } = action; | |
return Object.assign({}, state, { result: payload.result }); | |
} | |
case ActionTypes.FAILURE:{ | |
const { payload } = action; | |
return Object.assign({}, state, { error: payload.error }); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment