简体   繁体   中英

Cannot read property “#” of null react

I am very new to react and I was trying to load profile picture from firebase database. Even tho the property is not null it keeps saying TypeError: Cannot read property 'pfpUrl' of null.

 import React from "react" import { NavLink } from "react-router-dom"; import { useState, useEffect } from "react" import firebase from "firebase"; import fire from "./firebase" import { useHistory } from "react" function Header(){ const [pfp, setPfp] = useState(null) const [userID, setUserID] = useState(null); firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserID(user.uid) firebase.database().ref("users/"+userID+"/public/profile/pic").on("value", (snapshot)=>{ setPfp(snapshot.val().pfpUrl) }) }else{ } }) function signOut(){ firebase.auth().signOut().then(()=>{ console.log("successfully signout") }) } return( <header> <div id = "hd-container"> <div id = "logo-contain"> <NavLink to = "/"><h1>Logo</h1></NavLink> </div> <div id ="search"> <div className = "bar"> <input id = "searchBar" placeholder = "search"></input> </div> <div className = "searchBtn"> <button id = "srhBtn">Search</button> </div> </div> <div id = "buttons"> <div className = "profile"> <NavLink to = {"users/"+userID}><img src = {pfp} height = "50" width = "50" /></NavLink> </div> <div className = "signout"> <button onClick = {signOut}>Sign Out</button> </div> </div> </div> </header> ) } export default Header;
Even tho the profile pic loads, the error keeps on coming, any fix?

Your use of setUserID(user.uid) will not immediately cause the userID variable to contain the new value. It will only contain that new value the next time the component renders (not this time it's about to render).

If you want to use the user's UID in the database query coming up immediately, you will need to use its value locally.

const uid = user.uid
setUserID(uid)
firebase.database().ref("users/"+ uid +"/public/profile/pic").on("value", (snapshot)=>{
    setPfp(snapshot.val().pfpUrl)
})

See that uid is a local variable whose value is able to be used immediately in the query.

First you need to execute your code inside useEffect because whenever you are setting state the api will keep on firing the api call. See below code and try display you value in console to verify its coming from backend.

useEffect(() => {
    firebase.auth().onAuthStateChanged((user)=>{
            if(user){
                setUserID(user.uid)
                firebase.database().ref("users/"+user.uid+"/public/profile/pic").on("value", (snapshot)=>{
                    setPfp(snapshot.val().pfpUrl)
                })
            }else{
                
            } 
        })
}, [])

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