1
votes

I'm looking for the best way to handle my fetching status in my app, the simplest way is to create an isFetching[actionName] for each action and then the state will look something like this:

state:{
todos:[...],
user[...],
isTodosFetching:true/false,
isUserFetching:true/false
}

but I'm looking for a more elegant way of storing fetching statuses in the store.

so I tried to think of an alternative way and thought about create a fetchingActionsReducer that will add each fetching action to a dict(object) in the store and then the state will look like this:

todos:[...],
user[...],
loadingTasks:{
isTodosFetching:true/false,
isUserFetching:true/false
}}```

now every component will get loadingTasks with mapStateToProps and that's it. 
this will reduce the boilerplate to one simple reducer and one action.
reducer:

export const loadingTasks = (state = {}, action) => { switch (action.type) { case START_LOADING_TASK: return Object.assign({}, state, { [action.payload]: true }); case END_LOADING_TASK: return Object.assign({}, state, { [action.payload]: false }); default: return state; } };

actions:

export const startLoadingTask = (taskName) => ({ type: START_LOADING_TASK, payload: taskName, });

export const endLoadingTask = (taskName) => ({ type: END_LOADING_TASK, payload: taskName, });```

I tried it it works perfect but I would like to know,
1. there is any better way to handle fetching status with redux? 2. now many portfolios will be subscribed to the loadingTasks state and I'm afraid it will cause performance issues. (for every change in the loading tasks all react will run the digging algorithm for all the components subscribed)

1
Can you take a look at this question please?. I have explained how to leverage redux for conditional rendering.Ajin Kabeer

1 Answers

0
votes

I suggest co-locating the fetching status with the resource being requested, for example:

state:{
  todos: {
    isFetching: true, // or false
    data: [/* ... */]
  },
  user: {
    isFetching: true, // or false
    data: [/* ... */]
  }
}

This way when the fetching status of todos change only the components dependant on todos will rerender.

This approach also enables additional statuses.

For example if the todos request fails you could have an error status. Or if the user request fails an error message providing some context, or even containing the error returned from the API:

state:{
  todos: {
    isFetching: false,
    hasError: true, // or false
    data: [/* ... */]
  },
  user: {
    isFetching: false,
    errorMessage: 'Please check username exists', // or null
    data: [/* ... */]
  }
}