Under the root folder, create Auth.js.
Then go inside Auth.js. First, we need to import useEffect
, createContext
, getAuth
and useState
.
import React, { useEffect, useContext, createContext, useState } from 'react';import { auth } from './firebase';
Then we create AuthContext
.
Create the AuthProvider which allow to pass the children into it. Then create a state called currentUser, we will pass this information to all components.
Inside useEffect
, we are going to check if the user exists. If not, we will console.log('no user')
and clear the cookies.
If there is a user, we will get the token and then log the token at console.
const AuthContext = createContext({});export const AuthProvider = ({ children }) => {const [currentUser, setCurrentUser] = useState(null)useEffect(() => {return auth.onIdTokenChanged(async (user) => {