cra-template-redux
cra-template-redux copied to clipboard
Suggested improvement: add an API call (fetch)
The async example is good, but perhaps not as universally applicable as a REST API call. What about adding a few state modifications to the slice?
fetchTodoStart: (state, action) => {
state.todoLoading = true;
state.todo = null;
state.todoError = null;
},
fetchTodoSuccess: (state, action) => {
state.todoLoading = false;
state.todo = action.payload;
},
fetchTodoFailure: (state, action) => {
state.todoLoading = false;
state.todoError = action.payload;
},
Then using fetch to get the content?
export const fetchTodo = (id) => async (dispatch) => {
dispatch(fetchTodoStart(id));
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todo = await response.json();
dispatch(fetchTodoSuccess(todo));
} catch (e) {
dispatch(fetchTodoFailure(JSON.stringify(e)));
}
};