Home > database >  Action is called but didn't executed in redux
Action is called but didn't executed in redux

Time:11-03

I was trying to build login application. Its working fine but on refresh all the states are lost. When I log in the application [ from login page ] a token is received from backend, i store that token locally and calls the action "loadUser" which ultimately gets the user info and stores it. I was planning to use same action whenever my page is reloaded. Since my Navbar page is common to all the pages so i created was using useEffect hook to call loadUser action from there itself.

import React, { useEffect, Fragment } from "react";
import { useHistory } from "react-router";
import logo from "../../resources/images/desi-hip-hop.png";
import { useDispatch, useSelector } from "react-redux";
import { userActions } from "../../state/actions";
import LogoutGoogle from "../auth/LogoutGoogle";
const Navbar = (props) => {
  const dispatch = useDispatch();
  const history = useHistory();
  const isAuthenticated = useSelector((state) => state.user.isAuthenticated);

  useEffect(() => {
    try {
      dispatch(userActions.loadUser);
    } catch (error) {
      console.log("Error while loading user call");
    }
  }, []);

From here i am exporting my action which is being used in navBar to call the action. enter image description here

//Will store logged in or Signed up user
export const loadUser = () => async (dispatch) => {
  console.log("load User is called");
  setAuthToken(localStorage.token);
  try {
    const res = await axios.get("/auth");
    console.log("loading user with value"   res);
    dispatch({
      type: LOAD_USER,
      payload: res.data,
    });
    console.log("loading user  completed");
  } catch (error) {
    //TODO
    dispatch({
      type: AUTH_FAIL,
      payload: error.response.data.msg,
    });
  }
};

the following action i.e. loadUser works fine when called from other actions but not when we are refreshing window. It shows following behavior while debugging.

  1. My useEffect is called

enter image description here

  1. It reaches till here but doesn't go inside the code enter image description here

CodePudding user response:

The answer is quite simple:)

In useEffect you should provide as argument to dispatch function, that takes dispatch as an argument and does some logic.

You are providing function userActions.loadUser, that returns another function. This returned function is never executed.

Simply change dispatch(userActions.loadUser) to dispatch(userActions.loadUser()) and everything should work

  • Related