0

I want to update a specific property in each object in redux state, and assume I have this kind of main state

networkFailure: true
employer: {
  signUp: {
    data: null
    error: null
    loading: true
  }
}
user: {
  signUp: {
    data: null
    error: null
    loading: false
  }
}

Assume I have faced to a network failure, then the networkFailure state becomes true , and with that I need to fail(false) loading signUp state of the employer and all loading status to the false value of other objects too

Is that possible to do this in one reducer? or any suggestions for do it in a better way? I have setup 3 reducer functions for employer, user and network

SFernando
  • 1,074
  • 10
  • 35

2 Answers2

0

There are two ways as I think: 1. Using the redux-thunk and dispatch an action and then dispatch 3 actions inside the action function which return dispatch function to you.something like this:

function setErrorAction() {
  return dispatch => {
      const networkError = {type: "network/singup/error"}
      const employer Error = {type: "employer/singup/error"}
      const userError = {type: "user/singup/error"}

      dispatch(networkError)
      dispatch(employer)
      dispatch(userError)
  }
}
  1. Write a hook function that it has access to the dispatch function which exposed function to dispatch actions that when you call the hook function, it will dispatch actions to the reducers but it is a way to centralizing the business. something like this:
import {useDispatch} from "react-redux";

function useAuthError() {
   const dispatch = useDispatch();

   function setError() {
      const networkError = {type: "network/singup/error"}
      const employer Error = {type: "employer/singup/error"}
      const userError = {type: "user/singup/error"}

      dispatch(networkError)
      dispatch(employer)
      dispatch(userError)
   };

   return {
      setError
   }
}
Ali Torki
  • 1,929
  • 16
  • 26
  • 1
    This is a good solution, but dispatching multiple actions is not good for this kind of thing, lets say I have 10 more states then I have to dispatch 10 actions – SFernando Feb 04 '20 at 07:03
  • you're right, but redux can't update multiple reducers by one action, you know, redux doesn't have this feature. – Ali Torki Feb 04 '20 at 07:46
0

One answer is found from here

Actually when a network failure happened, for me it is fine to reset the application state,

So I have reset the application state in the root reducer

const rootReducer = (state, action) => {
  if (action.type === 'NETWORK_ERROR') {
    state = undefined
  }
  return appReducer(state, action)
}

this will keep other reducer's state to its default one

SFernando
  • 1,074
  • 10
  • 35