Last active
February 13, 2020 09:17
-
-
Save zzdjk6/69a9821c97a6eb669ccc9da53fec5e74 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
// 1. Define the constants that are used as action types | |
const FETCH_DATA_REQUEST = 'FETCH_DATA/REQUEST'; | |
const FETCH_DATA_SUCCESS = 'FETCH_DATA/SUCCESS'; | |
const FETCH_DATA_FAILURE = 'FETCH_DATA/FAILURE'; | |
// 2. Define synchronous action creators (following Flux Standard Action) | |
const fetchDataRequest = (payload?: any) => { | |
if (typeof payload === 'undefined') { | |
return { | |
type: FETCH_DATA_REQUEST | |
}; | |
} | |
return { | |
type: FETCH_DATA_REQUEST, | |
payload | |
}; | |
}; | |
const fetchDataSuccess = (payload: DataType) => { | |
return { | |
type: FETCH_DATA_SUCCESS, | |
payload | |
}; | |
}; | |
const fetchDataFailure = (payload: Error) => { | |
return { | |
type: FETCH_DATA_FAILURE, | |
payload, | |
error: true | |
}; | |
}; | |
// There is a simplied version if you are using `redux-action` | |
// const fetchDataRequest: (payload?: any) => Action<any> = createAction(FETCH_DATA_REQUEST); | |
// const fetchDataSuccess: (payload: DataType) => Action<DataType> = createAction(FETCH_DATA_SUCCESS); | |
// const fetchDataFailure: (payload: Error) => Action<Error> = createAction(FETCH_DATA_FAILURE); | |
// 3. Define thunk action creator | |
const fetchData = (id: number) => async (dispatch: Dispatch) => { | |
await dispatch(fetchDataRequest(id)); | |
try { | |
const data = await api.fetchData(id); | |
return await dispatch(fetchDataSuccess(data)); | |
} catch (e) { | |
await dispatch(fetchDataFailure(e)); | |
throw e; | |
} | |
}; | |
// 4. Handle actions in reducers | |
switch (action.type) { | |
case FETCH_DATA_REQUEST: | |
return { | |
...state, | |
isFetching: true, | |
error: null | |
}; | |
case FETCH_DATA_SUCCESS: | |
return { | |
...state, | |
isFetching: false, | |
data: action.payload, | |
error: null | |
}; | |
case FETCH_DATA_FAILURE: | |
return { | |
...state, | |
isFetching: false, | |
error: action.payload | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment