简体   繁体   English

为什么页面刷新时firebase的实时数据库不加载数据

[英]Why is firebase's Realtime Database not loading data when page refreshes

I am using Firebase Realtime Database for a site I am developing with React.我正在将 Firebase 实时数据库用于我正在使用 React 开发的站点。 In a useEffect method, I am using Firebase's get method to receive all the data from the database and it works when I switch from the home page back to the page I am displaying the data on but it doesn't work when I refresh my page.在 useEffect 方法中,我使用 Firebase 的 get 方法从数据库接收所有数据,当我从主页切换回显示数据的页面时它可以工作,但刷新页面时它不起作用. I have tried using an async await function, console.logging everything I could think of, and re-writing the entire code.我尝试过使用异步等待 function,console.logging 我能想到的一切,并重写整个代码。

This is my useEffect method that fetches an input that was previously saved to the database.这是我的 useEffect 方法,它获取以前保存到数据库的输入。 If I switch from the 'Journal' Router page to Home page and back, it loads correctly but it doesn't load correctly if I refresh the page.如果我从“日志”路由器页面切换到主页并返回,它会正确加载,但如果我刷新页面,它不会正确加载。 When I refresh, it console.logs 'No Data' but I know the data exists because when I switch between router pages it does load.当我刷新时,它 console.logs 'No Data' 但我知道数据存在,因为当我在路由器页面之间切换时它会加载。

useEffect(() => {
        const dbRef = ref(getDatabase())
        
        //Fetches dreams from firebase's database
        get(child(dbRef, `/${user.uid}/dreams`)).then(snapshot => {
            if (snapshot.exists()){
                const dreams = snapshot.val()
                Object.values(dreams).forEach(dream => {
                    setUserDreams(prev => [...prev, dream])
                })
            } else {
                console.log('No Data')
            }
        }).catch(err => {
            console.error(err);
        })
...
}, [])

The JSON structure of the database is basically this数据库的JSON结构基本是这样的

"USER_ID" : {
    "dreams" : [{"RANDOM_UUID" : {...}}],
    "tags" : [{"RANDOM_UUID" : {...}}]
}

The user ID is the uid that firebase generates in their user authentication feature and it doesn't change and the random uuid is a random string generated from the firebase uuidv4 method.用户 ID 是 firebase 在其用户身份验证功能中生成的 uid,它不会更改,随机 uuid 是从 firebase uuidv4 方法生成的随机字符串。

This is how the user variable is populated:这是用户变量的填充方式:

import {createContext, useContext, useEffect, useState} from 'react'
import {
    createUserWithEmailAndPassword,
    signInWithEmailAndPassword,
    signOut,
    updateProfile,
    onAuthStateChanged
} from 'firebase/auth';
import { auth } from '../firebase-config';

const UserContext = createContext();

export const AuthContextProvider = ({children}) => {
    const [user, setUser] = useState({})

    const createUser = (email, password) => {
        return createUserWithEmailAndPassword(auth, email, password);
    }

    const updateUsername = (username) => {
        return updateProfile(auth.currentUser, {
            displayName: username
        })
    }

    const signIn = (email, password) => {
        return signInWithEmailAndPassword(auth, email, password);
    }

    const logout = () => {
        return signOut(auth);
    }

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
            console.log(currentUser)
            setUser(currentUser)
        })
        return () => {
            unsubscribe()
        }
    }, [])

    return (
        <UserContext.Provider value={{createUser, user, logout, signIn, updateUsername}}>
            {children}
        </UserContext.Provider>
    )
}

export const UserAuth = () => {
    return useContext(UserContext)
}

Sorry if this is a bit weird but I figured out the issue.对不起,如果这有点奇怪,但我发现了这个问题。 After logging the user variable in my journal file, I learned that it isn't populated until after that useEffect is ran so I just put user as the dependency variable in my useEffect hook so it waits until it is populated to run that hook.在我的日志文件中记录用户变量后,我了解到它直到运行useEffect之后才会填充,所以我只是将user作为依赖变量放在我的 useEffect 钩子中,所以它会等到它被填充以运行该钩子。

useEffect(() => {
        const dbRef = ref(getDatabase())
        
        //Fetches dreams from firebase's database
        get(child(dbRef, `/${user.uid}/dreams`)).then(snapshot => {
            if (snapshot.exists()){
                const dreams = snapshot.val()
                Object.values(dreams).forEach(dream => {
                    setUserDreams(prev => [...prev, dream])
                })
            } else {
                console.log('No Data')
            }
        }).catch(err => {
            console.error(err);
        })
...
}, [user])

This is what worked, the only thing changed was the dependency array.这是有效的,唯一改变的是依赖数组。 Meaning, the user variable was populated after the useEffect hook ran which is what made me have issues.意思是,在useEffect挂钩运行后填充了user变量,这让我遇到了问题。 Thanks for the commenter that helped me out!感谢帮助我的评论者!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM