cra-template-redux icon indicating copy to clipboard operation
cra-template-redux copied to clipboard

Suggested improvement: add an API call (fetch)

Open a-h opened this issue 4 years ago • 0 comments

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)));
  }
};

a-h avatar Mar 29 '20 17:03 a-h