Search code examples
reactjsreact-hooksuse-effectreact-context

using useEffect to grab data from context on page load


i need help figuring this out. I have a token which i store in a context globalContext. I want to fetch that token when the page loads and make a request with it. But seems to me that when i try to fetch it using useEffect hook with a [] dependency, and try to log it to console it shows an empty line logged like this

enter image description here

if i remove the dependency [] on the hook. it logs the same line for 3-4 seconds and later it starts logging the token as it should be. What do you think is the issue here?

GlobalContext

const GlobalContextProvider = (props) => {
  const [globalState, setGlobalState] = useState({
    userType: "", //Organisation or Changemaker
    showModal: false,
    modalContent: "", //profile, editprofile, studentlisting, orglisting, createlisting
    access_token: "",
    isSigningUp: false,
  });

  const [profile, setProfile] = useState({});

  const updateGlobalState = (key, val) => {
    setGlobalState((prevState) => ({
      ...prevState,
      [key]: val,
    }));
  };

  return (
    <GlobalContext.Provider
      value={{ globalState, updateGlobalState, profile, setProfile }}
    >
      {props.children}
    </GlobalContext.Provider>
  );
};

useEffect hook

  useEffect(() => {
    
    console.log(globalState.access_token);
  }, []);


Solution

  • You need to add globalState.access_token as a dependancy of your useEffect callback. Example:

    useEffect(() => {
      console.log(globalState.access_token);
    }, [globalState.access_token])
    

    Note this function will fire everytime the value of globalState.access_token changes.