Search code examples
reactjsreact-reduxredux-thunk

Redux Thunk action not executing


I'm using React with Redux and Thunk as middleware to handle async actions. I have a button where when a user clicks it, it should logout the user. Currently when I click the button nothing happens. I've added a console.log in the attemptLogout but even that isn't triggering... I can't figure out why, was hoping someone could review my code and provide some feedback.

NavProfile.js

const onLogout = () => {
  attemptLogout();
};

<Menu.Item key={menuItem.legth + 1} onClick={onLogout}>
    <span>
        <LogoutOutlined className="mr-3" />
        <span className="font-weight-normal">Logout</span>
    </span>
</Menu.Item>

redux/actions/Auth.js

export const logout = () => ({
  type: LOGOUT,
});

redux/reducers/Auth.js

const initialState = {
  token: localStorage.getItem('token'),
  isAuthenticated: false,
  loading: true,
  error: {},
};

const auth = (state = initialState, action) => {
  const { type, payload } = action;

  switch (type) {
    ...
    case LOGOUT:
      return {
        ...state,
        token: null,
        isAuthenticated: false,
        loading: false,
      };
    default:
      return state;
  }
};

redux/reducers/User.js

const initialState = {
  user: null,
  loading: true,
  error: {},
};

const user = (state = initialState, action) => {
  const { type, payload } = action;

  switch (type) {
    ...
    case LOGOUT:
      return {
        ...state,
        loading: false,
        user: null,
      };
    default:
      return state;
  }
};

redux/thunks/Auth.js

// Logout User
export const attemptLogout = () => async (dispatch) => {
  console.log('Logout');
  dispatch(logout());
  dispatch(push('/auth/login'));
};

Solution

  • You need to dispatch attemptLogout. Otherwise the thunk never passed through redux middleware and is never called.

    const onLogout = () => {
      dispatch(attemptLogout());
    };
    

    To access dispatch you can use the hook in your menu/menu item component. Something like:

    import {useDispatch} from 'react-redux';
    
    function MenuExample() {
      const dispatch = useDispatch();
    
      const onLogout = () => {
        dispatch(attemptLogout());
      };
    
      ...
    }