Create WhatsApp clone with Next.js Part 17 Add AuthProvider

Detect whether user sign in or not

Ckmobile
2 min readNov 11, 2021

Source code

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) => {

--

--

Ckmobile
Ckmobile

Written by Ckmobile

Teaching JavasScript, React, React Native, MongoDB and NodeJS https://linktr.ee/ckmobile

No responses yet