Skip to content

Instantly share code, notes, and snippets.

@sbycrosz
Created March 8, 2018 07:16
Show Gist options
  • Save sbycrosz/5b19b30d7343d0b46e581c413e4e0379 to your computer and use it in GitHub Desktop.
Save sbycrosz/5b19b30d7343d0b46e581c413e4e0379 to your computer and use it in GitHub Desktop.
SimpleReducer_AsyncInRedux.js
// todo/actions.js
export const getTodos = (dispatch) => () => {
dispatch({ type: 'GET_TODOS_REQUEST' });
return fetch('/api/v1/todos')
.then((todos) => dispatch({ type: 'GET_TODOS_SUCCESS', payload: todos })
.catch((error) => dispatch({ type: 'GET_TODOS_FAILURE', payload: error, error: true });
};
// todo/reducer.js
const initialState = { todos: [] };
export const todoReducer = (state = initialState, action) => {
switch(action.type) {
case 'GET_TODOS_REQUEST':
return { ...state, isFetching: true };
case 'GET_TODOS_SUCCESS':
return { ...state, isFetching: false, todos: action.payload };
case 'GET_TODOS_FAILURE':
return { ...state, isFetching: false, errorMessage: action.payload.message };
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment