Home > Blockchain >  How to get session data in next-auth after loading is done
How to get session data in next-auth after loading is done

Time:11-07

I am trying to get data using useSession, and this data I store in my state, but when I get data using this, it returns me null object since data is still in loading state.
Is there any way I can get data only after status is not loading and till then block the page?

const { data: session, status } = useSession();
  useEffect(() => {
    const { data } = getCookieData(session);
    if (data) setUser(() => data.user);
  }, []);

CodePudding user response:

Comment turned into an answer:

useSession changes the state after the status changes. If you want the code inside the useEffect to run after state changes, you probably want to put that state inside the brackets, so this code:

  useEffect(() => {
    const { data } = getCookieData(session);
    if (data) setUser(() => data.user);
  }, []);

Would become this

  useEffect(() => {
    const { data } = getCookieData(session);
    if (data) setUser(() => data.user);
  }, [data,status]);

And in general whenever you need to trigger some function every time a particular prop or state changes you should place those variables inside the useEffect()

More info about useEffect and lifecycles in the docs: https://reactjs.org/docs/hooks-effect.html

  • Related