Last active
March 23, 2018 09:45
-
-
Save SuperOleg39/9d1e9cdbc1722bdfbbda964b9c657e2e 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
| export enum constants { | |
| FETCH_REQUEST = 'module/FETCH_REQUEST', | |
| FETCH_SUCCESS = 'module/FETCH_SUCCESS', | |
| FETCH_FAILURE = 'module/FETCH_FAILURE' | |
| } | |
| interface IState { | |
| isFetching: Readonly<boolean>; | |
| isError: Readonly<boolean>; | |
| data: Readonly<IApiResponse>; | |
| } | |
| const initialState = { | |
| isFetching: false, | |
| isError: false, | |
| data: null | |
| }; | |
| export const selectors = { | |
| getData: (state: IState): IApiResponse => state.ducks.data, | |
| isFetching: (state: IState): boolean => state.ducks.isFetching, | |
| isError: (state: IState): boolean => state.ducks.isError | |
| }; | |
| export type actions = { | |
| fetchRequest: { | |
| type: constants.FETCH_REQUEST; | |
| }; | |
| fetchSuccess: { | |
| type: constants.FETCH_SUCCESS; | |
| payload: IApiResponse; | |
| }; | |
| fetchFailure: { | |
| type: constants.FETCH_FAILURE; | |
| }; | |
| } | |
| type RootAction = actions[keyof actions]; | |
| const reducer = (state = initialState, action: RootAction): IState => { | |
| switch (action.type) { | |
| case constants.FETCH_REQUEST: { | |
| return { | |
| ...state, | |
| isFetching: true | |
| }; | |
| } | |
| case constants.FETCH_SUCCESS: { | |
| return { | |
| ...state, | |
| data: action.payload, | |
| isError: false, | |
| isFetching: false | |
| }; | |
| } | |
| case constants.FETCH_FAILURE: { | |
| return { | |
| ...state, | |
| isError: true, | |
| isFetching: false | |
| }; | |
| } | |
| default: { | |
| return state; | |
| } | |
| } | |
| }; | |
| export default reducer; | |
| export const actionCreators = { | |
| fetchRequest: (): actions['fetchRequest'] => ({ type: constants.FETCH_REQUEST }), | |
| fetchSuccess: (payload: IApiResponse): actions['fetchSuccess'] => ({ type: constants.FETCH_SUCCESS, payload }), | |
| fetchFailure: (): actions['fetchFailure'] => ({ type: constants.FETCH_FAILURE }), | |
| }; | |
| export const thunkActionCreators = { | |
| fetch: () => async (dispatch, getState) => { | |
| dispatch(actionCreators.fetchRequest()); | |
| try { | |
| const response = await fetch('api/v1/data'); | |
| dispatch(actionCreators.fetchSuccess(response.data)); | |
| } catch (reason) { | |
| dispatch(actionCreators.fetchFailure()); | |
| throw new Error(reason); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment