简体   繁体   中英

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. 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. I have tried using an async await function, console.logging everything I could think of, and re-writing the entire code.

This is my useEffect method that fetches an input that was previously saved to the database. 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.

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

"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.

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(() => {
        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. Thanks for the commenter that helped me out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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