0

I'm working on a react-firebase project, where i send token to backend to authenticate the user, but after one hour I need to refresh the page to authenticate the same user because of expiry of refresh tokens.

  useEffect(() => {
    auth.onAuthStateChanged((result) => {
      if (result) {
        console.log("user", result)
        console.log("location", location.pathname)
        var token = result.accessToken;
        const displayName = result.displayName;
        const email = result.email;
        const photoURL = result.photoURL;
        const phoneNumber = result.phoneNumber;
        const uid = result.uid;

        const user = { displayName, email, photoURL, phoneNumber, uid }
        createUserDocument(user);

        localStorage.setItem("name", displayName);
        localStorage.setItem("email", email);
        localStorage.setItem("phoneNumber", phoneNumber);
        localStorage.setItem("auth", true);
        localStorage.setItem("token", token);
        localStorage.setItem("photoURL", photoURL);
        setPhotoUrl(photoURL)
        dispatch({ type: UPDATE_USER, payload: user })
      }
    })
  }, [])

Here in the above code I've used that code inside the componentdidmount, where authentication happens only once, but if I remove those bracket and use componentDidUpdate, then it'll be a performance concern. How to resolve this kind of issue.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Sushanth
  • 15
  • 1
  • 6
  • 1
    Firebase SDK does all the job for you. You can simply use `getIdToken()` method to get a valid token every time before you make an API request. Check the linked answer for more information. – Dharmaraj Oct 24 '22 at 11:03
  • useEffect(() => { auth?.currentUser?.getIdToken(true).then(function (idToken) { localStorage.setItem("token", idToken); }).catch(function (error) { console.log("error") }); }, [location]) Hey, I have used the above method which u recommended, but still I'm getting the same error. I tried several ways but still not able to fix this. – Sushanth Dec 18 '22 at 06:53

0 Answers0