-1

I have a firebase app in which user can log in using the firebase Google authentication. After the user sign in with google their data is written to database after a sign-up then they are redirected to dashboard. Also the details of the user is stored using context API. But when I refresh the page it logs the user out and makes them sign in again .Is there a way I can keep this user data even after page refresh. (user data in an object)

I tried fetching user from database on refresh but that didn't work out

1 Answers1

0

You can use a custom local storage hook & context api for achieve this.

Here is the local storage hook:

import React from "react"
import { useState, useEffect } from "react"

type ReturnType<T> = [
    T | undefined,
    React.Dispatch<React.SetStateAction<T | undefined>>
]

const useLocalStorage = <T,>(key: string, initialValue?: T): ReturnType<T> => {
    const [state, setState] = useState<T | undefined>(() => {
        if (!initialValue) return
        try {
            const value = localStorage.getItem(key)
            return value ? JSON.parse(value) : initialValue
        } catch (error) {
            return initialValue
        }
    })

    useEffect(() => {
        if (state) {
            try {
                localStorage.setItem(key, JSON.stringify(state))
            } catch (error) {
                console.log(error)
            }
        }
    }, [state, key])

    return [state, setState]
}

export { useLocalStorage }

and the context for auth:

import { useLocalStorage } from "../hooks/useLocalStorage"

export interface Auth {
    username?: string
    roles?: Array<string>
    permissions?: Array<string>
    token?: string
}

export interface AuthContextInstance {
    auth?: Auth
    setAuth: React.Dispatch<React.SetStateAction<Auth | undefined>>
    unsetAuth: () => void
}

const AuthContext = createContext<AuthContextInstance>({
    setAuth: () => {
        return
    },
    unsetAuth: () => {
        return
    },
})
alp
  • 1
  • 1
  • 4