How to return empty action when dispatching an Async action in React js?

Viewed 383

I have a react application and i'm dispatching below async action

#landingScreen.js

useEffect(() => {
 dispatch(updateRestoreProgress(isAuthenticated, restoringProgressCompleted, mail, currentlyRestoringCount));
}, [isAuthenticated]);

and in my action.js

# action.js

export const updateRestoreProgress = ( isAuthenticated, restoringProgressCompleted, mail, currentlyRestoringCount) => {

  if (isAuthenticated && !restoringProgressCompleted) {
     return async (dispatch) => {
        ... async calls
        ... dispatch(methods)
        ...
     }
  }
  // here I need to return and empty action to avoid the console error
}

When i run the above code It's working when the condition "isAuthenticated && !restoringProgressCompleted" becomes true. But if not, I get an error like below,

Uncaught (in promise) TypeError: Cannot read property 'type' of undefined

suggest a solution pls

1 Answers

If you just need to return/dispatch an empty action you can use { type: null }.

export const updateRestoreProgress = (
  isAuthenticated,
  restoringProgressCompleted,
  mail,
  currentlyRestoringCount
) => {
  if (isAuthenticated && !restoringProgressCompleted) {
     return async (dispatch) => {
        ... async calls
        ... dispatch(methods)
        ...
     }
  }
  return { type: null };
}

So long as you have no reducer cases that handle a null action.type this should be safe to use.

If you want to be extra clear about this, create a noop (no-op) action creator and manually invoke it to return the action object.

const noop = () => ({ type: 'NOOP' });

...

export const updateRestoreProgress = (
  isAuthenticated,
  restoringProgressCompleted,
  mail,
  currentlyRestoringCount
) => {
  if (isAuthenticated && !restoringProgressCompleted) {
     return async (dispatch) => {
        ... async calls
        ... dispatch(methods)
        ...
     }
  }
  return noop();
}
Related