react-token-auth icon indicating copy to clipboard operation
react-token-auth copied to clipboard

Clarifying why useAuth() returns false, then true, without refreshing?

Open RylanSchaeffer opened this issue 2 years ago • 3 comments

Hi! I'm using react-token-auth and I'm noticing something odd. First, here's my code for createAuthProvider

export const {useAuth, authFetch, login, logout} = createAuthProvider({
  accessTokenKey: 'access_token',
  onUpdateToken: (token) => fetch(
    `${process.env.REACT_APP_URL_BACKEND}/refresh`,
    {
      method: 'POST',
      body: token.access_token
    }).then(r => r.json())
});

And here's my simple App() component:


function App() {

  const navigate = useNavigate();
  const [isSignedIn] = useAuth();

  console.log('App isSignedIn: ', isSignedIn)
}

When I access the page, isSignedIn is logged as false and then without refreshing the page, is logged again as true:

App isSignedIn:  false [App.js:33]
App isSignedIn:  true [App.js:33]

Why is the value of isSignedIn changing without me navigating around the page? I thought this might be due to React StrictMode but I have that disabled.

RylanSchaeffer avatar Jun 14 '22 16:06 RylanSchaeffer

I just saw the README says "The hook useAuth might be used to get access to the auth from React component to render (and rerender) the app depending on the current auth state."

Could that explain what I'm seeing?

RylanSchaeffer avatar Jun 14 '22 16:06 RylanSchaeffer

Hi did you find a way how to fix that ? I'm running into the same situation, first I have false then true and it creates some flickering

Oubaluna avatar Dec 30 '23 17:12 Oubaluna

Ok I know it's an old discussion but I found a trick to always wait useAuth is finished. Also as I plan my redirection base on logged because it was first false it was annoying to be redirect to the login page when you refresh your protected page.

const [loading, setLoading] = useState(true);
  const [logged, session] = useAuth();

  // Handle to not have redirection on refresh
  useEffect(() => {
    setLoading(false);
  }, [logged]);

  if (loading) {
    return null
  }

Oubaluna avatar Dec 30 '23 17:12 Oubaluna