是否有一种方法可以在页面刷新后保留用户数据[重复]

问题描述 投票:0回答:1

我有一个 firebase 应用程序,用户可以在其中使用 firebase Google 身份验证登录。在用户使用谷歌登录后,他们的数据在注册后被写入数据库,然后他们被重定向到仪表板。用户的详细信息也使用上下文 API 存储。但是当我刷新页面时,它会将用户注销并让他们再次登录。有没有一种方法可以在页面刷新后保留这些用户数据。 (对象中的用户数据)

我尝试在刷新时从数据库中获取用户,但没有成功

javascript reactjs authentication local-storage react-context
1个回答
0
投票

您可以使用自定义本地存储挂钩和上下文 api 来实现此目的。

这里是本地存储挂钩:

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 }

以及 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
    },
})
© www.soinside.com 2019 - 2024. All rights reserved.