Avoiding multiple API calls due to rerenders in React with Firebase auth - reactjs

My web app uses Firebase Auth to handle user authentication along with a backend API, these are provided to the React app as a provider. The idea is that the backend API will verify the user's token when they sign in and deal with any custom claims / data that needs to be sent to the client.
The problem I'm having is that the provider is rerendering multiple times during the login flow, and each rerender is making an API call. I've managed to get the amount of rerenders down to two, but if I add other 'features' to the provider (e.g update the user's state if their access should change) then this adds to the amount of rerenders, sometimes exponentially, which leads me to suspect that the provider is rerendering as a result of setUserState being called, perhaps unnecessarily. Either way, it is clearly indicative of a problem somewhere in my code, which I've included below:
import {useState, useContext, createContext, useEffect} from 'react'
import {auth, provider} from './firebase'
import {getAuth, onAuthStateChanged, signInWithPopup, signOut} from 'firebase/auth'
import {api} from './axios'
export const UserContext = createContext(null)
export const useAuth = () => useContext(UserContext)
const verifyToken = token => {
return api({
method: 'post',
url: '/verifyToken',
headers: {token}
})
}
const UserProvider = props => {
const [userState, setUserState] = useState(null)
const [loading, setLoading] = useState(true)
const userSignedOut = async () => {
setLoading(true)
return await signOut(auth).then(() => {
setUserState(null)
}).catch(e => {
console.error(e)
}).finally(() => {
setLoading(false)
})
}
const userSignIn = async () => {
console.log('userSignIn')
setLoading(true)
try {
return await signInWithPopup(auth, provider)
} catch (e) {
console.error(e)
} finally {
if (!userState) {
setLoading(false)
}
}
}
const handleUserSignIn = async user => {
console.log('handleUserSignIn', user)
if (user && getAuth().currentUser) {
setLoading(true)
const idToken = await getAuth().currentUser.getIdToken(true)
const firebaseJWT = await getAuth().currentUser.getIdTokenResult()
if (!firebaseJWT) {throw(new Error('no jwt'))}
verifyToken(idToken).then(res => {
if (res.data.role !== firebaseJWT.claims.role) {
throw(new Error('role level claims mismatch'))
} else {
user.verifiedToken = res.data
console.log(`user ${user.uid} valid and token verified`, user)
setUserState(user)
setLoading(false)
}
}).catch(e => {
userSignedOut()
console.error('handleUserSignIn', e)
}).finally(() => {
setLoading(false)
})
} else {
console.log('no user')
userSignedOut()
}
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async user => {
console.log('onAuthStateChanged')
if (user?.uid && user.accessToken) {
await handleUserSignIn(user)
} else {
setUserState(null)
setLoading(false)
}
})
return () => unsubscribe()
}, [])
const value = {
signOut: userSignedOut, // for sign out button
signIn: userSignIn, // for sign in button
user: userState
}
return (
<UserContext.Provider value={value}>
{props.children}
</UserContext.Provider>
)
}
export default UserProvider
I tried to create a codesandbox for this, but unfortunately I was unable to simulate the Firebase auth functions.
The login flow is supposed to look like this:
The user signs in using their Google account.
The app is now loading, and the user cannot interact with it yet (they just get a spinning wheel).
The user's data and accessToken are sent to the backend API server. (function verifyToken)
The API server sets any custom claims and returns the verified token in its response, as well as the access that the user is supposed to have.
If the user's role / custom claims do not match what the API says they should be, the user is signed out.
The user's data is set using setUserState()
The app has finished loading, and the user is signed in.
I would like to avoid unnecessary rerenders and API calls and I suspect that some refactoring may be in order, but I'm not really sure what is best to do here.

Related

How Can I exist Queries When the User refresh the browser in react-query?

When refresh the Browser, inactive state queries have gone.
How Can I maintain queries When I refresh the Browser?
and also, I want to maintain userData when the pages go out
code like this.. (with zustand, react-query)
const {userId} = useParams();
const userData = useStore((state) => state.userData);
const {isLoading, data} = useQuery('user', () => getUser(userId), {
onSuccess: (res) => {
useStore.setState({userData: res.data});
},
onError: (err) => errorMsg(err),
});
getUser func
export const getUser = (userId)=>{
if(!userId) return;
return axios.get(`${API.user(userId)}`};
}
React Query provides experimental (as of June 2022) support for storing data in Local Storage:
import { persistQueryClient } from 'react-query/persistQueryClient-experimental'
import { createWebStoragePersistor } from 'react-query/createWebStoragePersistor-experimental'
// probably also supports session storage as the API is the same
const localStoragePersistor = createWebStoragePersistor({storage: window.localStorage})
// the queryClient you pass to QueryClientProvider
persistQueryClient({
queryClient,
persistor: localStoragePersistor,
})
Source: https://react-query.tanstack.com/plugins/persistQueryClient

best way to authenticate with SWR (firebase auth)

I'm doing project with React , firebase auth social signin(google, github provider) and backend(spring boot)
I'm wondering how can i use useSWR for global state for google userData
Here's my Code This is Login page simply i coded
In this page, I fetch userData(email, nickname ,, etc) with header's idToken(received from firebase auth) and backend validates idToken and send me a response about userData
This is not problem I guess.. But
// import GithubLogin from '#src/components/GithubLogin';
import GoogleLogin from '#src/components/GoogleLogin';
import { auth, signOut } from '#src/service/firebase';
import { fetcherWithToken } from '#src/utils/fetcher';
import React, { useEffect, useState } from 'react';
import useSWR from 'swr';
const Login = () => {
const [token, setToken] = useState<string | undefined>('');
const { data: userData, error } = useSWR(['/api/user/me', token], fetcherWithToken);
useEffect(() => {
auth.onAuthStateChanged(async (firebaseUser) => {
const token = await firebaseUser?.getIdToken();
sessionStorage.setItem('user', token!);
setToken(token);
});
}, []);
return (
<div>
<button onClick={signOut}>Logout</button>
<h2>Login Page</h2>
<GoogleLogin />
</div>
);
};
export default Login;
Here's Code about fetcher using in useSWR parameter
export const fetcherWithToken = async (url: string, token: string) => {
await axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
Content-Type: 'application/json',
},
withCredentials: true,
})
.then((res) => res.data)
.catch((err) => {
if (err) {
throw new Error('There is error on your site');
}
});
};
problem
I want to use userData from useSWR("/api/user/me", fetcherWithToken) in other page! (ex : Profile Page, header's Logout button visibility)
But for doing this, I have to pass idToken (Bearer ${token}) every single time i use useSWR for userData. const { data: userData, error } = useSWR(['/api/user/me', token], fetcherWithToken);
Like this.
What is the best way to use useSWR with header's token to use data in other pages too?
seriously, I'm considering using recoil, context api too.
but I don't want to.
You can make SWR calls reusable by wrapping them with a custom hook. See the SWR docs page below.
Make It Reusable
When building a web app, you might need to reuse the data in many
places of the UI. It is incredibly easy to create reusable data hooks
on top of SWR:
function useUser (id) {
const { data, error } = useSWR(`/api/user/${id}`, fetcher)
return {
user: data,
isLoading: !error && !data,
isError: error
}
}
And use it in your components:
function Avatar ({ id }) {
const { user, isLoading, isError } = useUser(id)
if (isLoading) return <Spinner />
if (isError) return <Error />
return <img src={user.avatar} />
}

How to get Firestore document string to display? Can't perform state update, async function in useEffect

I have an AuthProvider/context providing firebase authentication. In a lower component I'm trying to render current user data from Firestore, such as a username, when they log in.
export function AuthProvider({ children }) {
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password)
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user);
setLoading(false);
if (currentUser) {
const docRef = db.collection("users").doc(currentUser.uid);
docRef.get().then(function(doc){
if(doc && doc.exists) {
setCurrentUsername(doc.data().username);
console.log(currentUsername)
}
}).catch(function(error) {
console.log("no document:", error);
});
} else {
// no user logged in
};
})
return unsubscribe
}, [login])
const value = {
currentUser, //firebase
signup,
login,
logout,
resetPassword,
currentFullname,
currentUsername,
currentEmail,
loading,
setLoading,
}
return (
<AuthContext.Provider
value={value}>
{children}
</AuthContext.Provider>
)
}
async function handleLogin(e) {
e.preventDefault()
try {
setError("")
setLoading(true)
await login(emailRef.current.value, passwordRef.current.value)
} catch {
setError("Incorrect email or password")
}
setLoading(false)
}
Only on logging in do I want to fetch additional user information from Firestore since Firebase authentication only has uid and email. I get the "can't perform React state update on an unmounted component" error.
Firestore data is structured like: collection("users") --> document (firebase uid) --> username: someUsername, firstname: bobSmith, etc...
Fixed! Code works for me now and has been updated to help any future people.
I had forgot to pass in a useContext value prop.
And then I changed the useEffect dependency array to login. Thanks Drew for guiding me through!

How to log in user with Google (through Firebase) in a React app with functional components?

I am trying to log in a user with Google in my React/Firebase app. I've followed a tutorial on youtube (https://www.youtube.com/watch?v=umr9eNbx3ag) but the results are different. When I click the Log In button, I get redirected to Google, choose an account and then get redirected to my site.
It seems as my 'if' statement never runs, auth.currentUser never evaluates to true.
This is my Firebase file
firebase.initializeApp(firebaseConfig)
export const firestore = firebase.firestore()
export const auth = firebase.auth()
export const provider = new firebase.auth.GoogleAuthProvider()
export const signInWithGoogle = () => auth.signInWithRedirect(provider)
export const signOut = () => auth.signOut()
export default firebase
This is my log in component
import { auth, signInWithGoogle, signOut } from '../../Firebase/Firebase'
const LoginOrRegister = () => {
const { username, setUsername, idToken, setIdToken } = useContext(Context)
useEffect(() => {
auth.onAuthStateChanged(async nextUser => {
if (auth.currentUser) {
setIdToken(await auth.currentUser.getIdToken())
setUsername(auth.currentUser.displayName)
} else {
setIdToken(null)
}
})
}, [])
return (
<div>
<LogInForm>
<button onClick={signInWithGoogle}> Log in with Google </button>
</div>
)
Since you are using signInWithRedirect you need to make use of auth.getRedirectResult() instead of auth.onAuthStateChanged as you are actually navigating away from the app and coming back in
Below code will work or you.
useEffect(() => {
auth
.getRedirectResult()
.then(function(result) {
console.log(result);
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
setToken(token);
// ...
}
// The signed-in user info.
var user = result.user;
console.log(user);
setData(user);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
console.log(errorCode, errorMessage);
// ...
});
}, []);
You can find the reference documentation here

#auth0/auth0-spa-js isAuthenticated is undefined on page refresh

I am working on the authentication of my app and I have managed to add login to my page. Users are able to login and their session is stored however as soon as I refresh the page their session is gone.
ReactJs + NextJS
I know there is getTokenSilently but it will return this when I call it!
error: "login_required"
error_description: "Login required"
state: "N3B+aWt4T1dBeGlibWsua2ZkdX5LTzR6T19ndTdXfkJ2Tm5kUzJIY3lXTQ=="
What am I doing wrong here?
My profile page!
useEffect(() => {
if (typeof window !== `undefined`) {
if (!loading && !isAuthenticated) {
loginWithRedirect({})
}
}
});
Home page which shows an icon if user is logged in!
<Button
className="account-button"
variant="textButton"
icon={<i className="flaticon-user" />}
aria-label="login"
title={loading ? 'loading' : isAuthenticated ? 'Hi' : 'login'}
/>
Auth service
// src/react-auth0-spa.js
import React, { useState, useEffect, useContext } from "react";
import createAuth0Client from "#auth0/auth0-spa-js";
const DEFAULT_REDIRECT_CALLBACK = () =>
window.history.replaceState({}, document.title, window.location.pathname);
export const Auth0Context = React.createContext();
export const useAuth0 = () => useContext(Auth0Context);
export const Auth0Provider = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
...initOptions
}) => {
const [isAuthenticated, setIsAuthenticated] = useState();
const [user, setUser] = useState();
const [auth0Client, setAuth0] = useState();
const [loading, setLoading] = useState(true);
const [popupOpen, setPopupOpen] = useState(false);
useEffect(() => {
const initAuth0 = async () => {
const auth0FromHook = await createAuth0Client(initOptions);
setAuth0(auth0FromHook);
if (window.location.search.includes("code=") &&
window.location.search.includes("state=")) {
const { appState } = await auth0FromHook.handleRedirectCallback();
onRedirectCallback(appState);
}
const isAuthenticated = await auth0FromHook.isAuthenticated();
setIsAuthenticated(isAuthenticated);
if (isAuthenticated) {
const user = await auth0FromHook.getUser();
setUser(user);
}
setLoading(false);
};
initAuth0();
// eslint-disable-next-line
}, []);
const loginWithPopup = async (params = {}) => {
setPopupOpen(true);
try {
await auth0Client.loginWithPopup(params);
} catch (error) {
console.error(error);
} finally {
setPopupOpen(false);
}
const user = await auth0Client.getUser();
setUser(user);
setIsAuthenticated(true);
};
const handleRedirectCallback = async () => {
setLoading(true);
await auth0Client.handleRedirectCallback();
const user = await auth0Client.getUser();
setLoading(false);
setIsAuthenticated(true);
setUser(user);
};
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
loginWithPopup,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
logout: (...p) => auth0Client.logout(...p)
}}
>
{children}
</Auth0Context.Provider>
);
};
The problem was using Brave Browser!!!!!! Detailed description here:
Right. So the silent authentication issue, the “login required” error, is what you get when your browser does not, or cannot, send the “auth0” cookie. This is the cookie that Auth0 leaves on the browser client once the user has a session with Auth0, i.e. the user has logged in through an interactive flow. You should be able to confirm this by looking at the network logs or analyzing the HAR output. The scenarios that work will have the cookie attached, whereas the ones that fail will not. If that’s the case, this is neither a sample nor SDK issue as they are not involved in the setting of that cookie; it is issued by the authorization server.
If the browser cannot sent this cookie, it’s most likely because of some software or browser extension or something which is blocking third-party tracking cookies. Safari does this by default thanks to its Intelligent Tracking Prevention (ITP2) 1 software that is built-in. This can explain why silent auth works in Chrome’s incognito mode but not in normal mode. If you’re running some extensions, you might want to disable some of them to narrow down which one is preventing the cookie from being sent.
What I can’t readily explain is how it works in Safari’s Private mode, as I thought ITP2 would block such cookies regardless. Let me get some clarity on that.
https://community.auth0.com/t/failed-silent-auth-login-required/33165/24

Resources