Authentication State
This page covers how you can subscribe and listen to the users authentication state, along with some useful tips to get the best results from the library.
Subscribing to updates
Applications taking advantage of Firebase Authentication will more than likely want to subscribe to the users authentication state, knowing whether they're signed-in our out.
The useAuthUser
hook enables you to do exactly this!
import { useAuthUser } from "@react-query-firebase/auth";
import { auth } from "./firebase";
function App() {
const user = useAuthUser(["user"], auth);
if (user.isLoading) {
return <div />;
}
if (user.data) {
return <div>Welcome {user.data.displayName}!</div>;
}
return <div>Not signed in.</div>;
}
Anytime your users state changes, the hooks data will be updated allowing you to reactively handle updates
within your application. If the user is authenticated, the hook returns the
User
interface, otherwise it's null
.
React Query options
The hook also allows us to provide React Query options, supporting all of the options the
useQuery
supports! For example, we could handle
side effects with ease:
const user = useAuthUser(["user"], auth, {
onSuccess(user) {
if (user) {
console.log("User is authenticated!", user);
}
},
onError(error) {
console.error("Failed to subscribe to users authentication state!");
},
});