Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
RylanSchaeffer opened this issue Jun 14, 2022 · 3 comments

Comments

@RylanSchaeffer
Copy link

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 RylanSchaeffer changed the title Clarifying why useAuth() returns different values? Clarifying why useAuth() returns false, then true, without refreshing? Jun 14, 2022
@RylanSchaeffer
Copy link
Author

RylanSchaeffer commented Jun 14, 2022

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
Copy link

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
Copy link

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
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants