obabichev / react-token-auth

84 stars 22 forks source link

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

Open RylanSchaeffer opened 2 years ago

RylanSchaeffer commented 2 years ago

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 commented 2 years ago

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?

Oubaluna commented 10 months ago

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 commented 10 months ago

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
  }