Search code examples
reactjsreduxdispatch

How to pass action creator (that uses dispatch) to store.dispatch?


I have an action creator in authActions.js as

export const loadUser = () => {
  console.log('loadUser running');
  return(dispatch, getState) => {
    //User loading
    console.log('about to call api');
    dispatch({type: USER_LOADING});

    console.log('dispatched user loading');
    return axios.get('api/auth/user', setConfig(getState)).then(res => {console.log(res.data); dispatch({type: USER_LOADED, payload: res.data});})
                                                            .catch(err => {
                                                                dispatch(returnErrors(err.response.data, err.response.status));
                                                                dispatch({type: AUTH_ERROR})
                                                            });
}

}

And I call this action creator in App.js since I want to load user details that is saved in local storage as soon as App renders.

function App() {
  useEffect(() => {
    console.log('loading user');
    store.dispatch(loadUser);
  }, []);
 return (
  <Provider store={store}>
   <div className="App">
    <AppNavbar />
    <ShoppingList />
   </div>
  </Provider>
 );
}

export default App;

But nothing gets executed inside of return of loadUser() function. Not even that console.log('about to call api') is working. How can I get this working?

Contents of authReducer.js is:

const initialState = {
 token: localStorage.getItem('token'),
 isAuthenticated: null,
 isLoading: false,
 user: null
};

const authReducer = (state = initialState, action) => {
 switch(action.type){
    case USER_LOADING:
        return {
            ...state,
            isLoading: true
        };
    case USER_LOADED:
        return {
            ...state,
            isAuthenticated: true,
            isLoading: false,
            user: action.payload
        };
    case AUTH_ERROR:
        localStorage.removeItem('token');
        return {
            ...state,
            token: null,
            user: null,
            isAuthenticated: false,
            isLoading: false
        };
    default:
        return state;
   }
  };

  export default authReducer;

Solution

  • You must call your loadUser action which is a thunk (function) in your case. And I assume you have added redux-thunk middleware, right?

    store.dispatch(loadUser());