BeHappy
BeHappy

Reputation: 3978

redux dispatch not work when use in axios interceptors

I want to show snackbar when axios return error. I use redux for config snackbar.

axiosAgent.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    console.log('object')
    const dispatch = useDispatch();
    dispatch({
      type: ActionsTypes.CHANGE_SNACKBAR_CONFIG,
      payload: { variant: "error", message: Strings.errors.problem }
    });
    dispatch({ type: ActionsTypes.CHANGE_SNACKBAR_SHOW, payload: true });
    return Promise.reject(error);
  }
);

and here is my snackbar component:

export default function Snackbar() {
  const open = useSelector(state => state.Snackbar.showSnackbar);
  const config = useSelector(state => state.Snackbar.snackbarConfig);
  const dispatch = useDispatch();

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }
    dispatch({ type: ActionsTypes.CHANGE_SNACKBAR_SHOW, payload: false });
  };
  useEffect(() => {
    console.log(config);
  }, [config]);
  return (
    <SB open={open} autoHideDuration={6000} onClose={handleClose}>
      <Alert onClose={handleClose} severity={config.variant}>
        {config.message}
      </Alert>
    </SB>
  );
}

but doesn't work. When I dispatch it from component it works but here not works.

Upvotes: 1

Views: 2757

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84902

Hooks, such as useDispatch(), can only be used in the body of a function component. You cannot use useDispatch in an interceptor. If you need to dispatch an action in an interceptor, you will need to have a reference to the store object, and call store.dispatch(/* action */)

Upvotes: 4

Related Questions