Redux Thunk
actions.js
export const gettingAsyncList = () => {
return {
type: GETTING_ASYNC_LIST,
}
}
export const getAsyncListSuccess = (data) => {
return {
type: GET_ASYNC_LIST_SUCCESS,
data: data,
}
}
export const getAsyncListFailure= (error) => {
return {
type: GET_ASYNC_LIST_FAILURE,
data: error,
}
}
export const fetchAsyncList = () => {
return (dispatch) => {
// Call an action
dispatch(gettingAsyncList())
// Fetch data
fetchSomeDataHere()
.then((response) => {
dispatch(getAsyncListSuccess(response))
})
.catch((error) => {
dispatch(getAsyncListFailure(error));
})
}
}
reducers.js
const defaultState = {
isFetching: false,
asyncList: [],
errorMsg: ''
}
export default function reducer(state = defaultState, action) {
if (action.type === GETTING_ASYNC_LIST) {
return {
...state,
isFetching: true
}
} else if (action.type === GET_ASYNC_LIST_SUCCESS) {
return {
...state,
isFetching: false,
asyncList: action.data
}
} else if (action.type === GET_ASYNC_LIST_FAILURE) {
return {
...state,
isFetching: false,
asyncList: [],
errorMsg: action.data
}
} else {
return state
}
}
Leave a Reply