W
W
webe2019-07-20 18:59:57
React
webe, 2019-07-20 18:59:57

How to change isFetching state inside one reducer?

There is a user entity, now I can display a list of users and add new ones.
in the future there will be EDIT_USER_ , as well as DELETE_USER_
I want to note that each request needs a preloader, i. the isFetching field, as the server does not work quickly.
in this example
1) one isFetching is used for all types of actions, which is not good.
2) 1 reducer is used for code compactness. (which is good for me)
How to do isFetching for each of the actions in terms of architecture?
I know that you can create 6 reducers and each will have its own isFetching , but this will worsen the readability of the store.
You can leave one reducer as it is now and do isFetchingGetUsers isFetchingAddUser isFetchingEditUser isFetchingDeleteUser inside one reducer, but this option is also not very good, we end up with a mess of different field names,
what to do? tell me plz.
Or does it still need to be divided into 6 reducers?

const initialState = { isFetching: false, error: null, data: [] };

export default (state = initialState, { type, payload }) => {
  switch (type) {
    case 'GET_USERS_REQUEST':
      return { ...state, isFetching: true };
    case 'GET_USERS_SUCCSESS':
      return { ...state, isFetching: false, data: payload };
    case 'GET_USERS_ERROR':
      return { ...state, isFetching: false };

    case 'ADD_USER_REQUEST':
      return { ...state, isFetching: true };
    case 'ADD_USER_SUCCSESS':
      return { ...state, isFetching: false };
    case 'ADD_USER_ERROR':
      return { ...state, isFetching: false };

    default:
      return state;
  }
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-21
@webe

The state of a collection of users is best stored in a single reducer.
If the application is meant to work with one active entity, then it is better to make a separate reducer for it. In this case, it may be convenient to use one key for editing, saving, and deleting.
If such keys are needed to work with the collection, for example, quick editing, adding and deleting in a table. Then you can use the state collection:

{
  isFetching: {
    'ALL': false,
    '122bc-e43gf-24002-12ea1-ca785': true,
  },
}

Where there is always a property for all entities and optionally added for the necessary elements by id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question