Home > database >  Why does it direct me back to login page even user is authenticated?
Why does it direct me back to login page even user is authenticated?

Time:12-05

When I log in to the page and refresh the page it takes me back to the login page. What I want to happen is that when user is authenticated still it directs from login page to home page and not the other way around and that it stays on home page even page is refreshed.

This is my app.js:

import React from "react"
import { BrowserRouter, Routes, Route, Navigate, useLocation } from "react-router-dom"

import AuthContextProvider from "../Contexts/AuthContext"
import { useAuth } from "../Contexts/AuthContext"

import Login from "../Pages/Authentication/Login"
import Home from "../Pages/Home"

const App = () => {
  return (
    <AuthContextProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route
            path="/home"
            element={
              <RequireAuth>
                <Home />
              </RequireAuth>
            }
          />
        </Routes>
      </BrowserRouter>
    </AuthContextProvider>
  )
}

function RequireAuth({ children }) {
  const { currentUser } = useAuth()
  return currentUser ? children : <Navigate to="/login" replace />
}

export default App

this is my auth context:

import React, { createContext, useContext, useEffect, useState } from "react"
import { auth } from "../firebase/Firebase-config"
import {
  signInWithEmailAndPassword,
  onAuthStateChanged,
  signOut,
} from "firebase/auth"

const AuthContext = createContext({
  currentUser: null,
  login: () => Promise,
  logout: () => Promise,
})

export const useAuth = () => useContext(AuthContext)

export default function AuthContextProvider({ children }) {
  const [currentUser, setCurrentUser] = useState(null)

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user ? user : null)
    })
    return () => {
      unsubscribe()
    }
  }, [])

  useEffect(() => {
    console.log("The user is", currentUser)
  }, [currentUser])

  function login(email, password) {
    return signInWithEmailAndPassword(auth, email, password)
  }

  function logout() {
    return signOut(auth)
  }

  const value = {
    currentUser,
    login,
    logout,
  }
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

is what the auth context returns

enter image description here

CodePudding user response:

You are storing your user in a state, that is why. When you refresh the page, everything will comes to his initial value. You do need to use cookies or localStorage with state to maintain the needed informations.

CodePudding user response:

you can use an undefined state if you want.

const [currentUser, setCurrentUser] = useState(undefined)

than the possible states of currentUser will be undefined, null, or the user and you can check for this. Default it will be undefined so just navigate if it is null.

function RequireAuth({ children }) {
  const { currentUser } = useAuth()
  if(currentUser) {
    return children;
  }
  if(currentUser === null) {
    return <Navigate to="/login" replace />;
  }
  return null;
}
  • Related