Can someone explain me why my code's useEffect() getting stuck in an infinite loop? I am practicing React and implimented a user profile page. The infinite loop is triggered when I upload a picture to firebase, My thought process was that when I upload the picture, coverUrl gets changed into the url of the picture, inside useEffect if I see a change in cover, I update my userData and database value with the uploaded picture.
Globalconfig holds some state variables which gets filled up during login (in a different page) and I use it in this page but wait for it load first
const ProPicAndCover = () => {
const Globalconfig = useContext(ConfigContext)
const [coverUrl, setCoverUrl] = useState('')
const [isReady, setIsReady] = useState(false)
useEffect(() => {
// Wait for data to load
if(Globalconfig.userData !== ""){
setIsReady(true)
}
if(coverUrl !== ""){
update(ref(getDatabase(),'users/' Globalconfig.userData.UID), {cover_picture_url: coverUrl})
getUserInfo(Globalconfig.UID, getDatabase(), Globalconfig.setUserData)
}
},[Globalconfig.userData])
if(isReady){
return(
<div id="ProPicAndCoverContainer">
<Container>
<input type="file" id="coverPhoto" hidden onChange={() => {
const file = document.getElementById("coverPhoto").files[0]
uploadImageAndgetUrl(getStorage(), file, Globalconfig.UID, setCoverUrl)
console.log(coverUrl)
}}></input>
{/* Code block to display if the user doo't have a cover photo */}
<div id="coverPic" style={{display: Globalconfig.userData.cover_picture_url === '' ? 'block' : 'none'}}>
<div id="coverText" onClick={() => {
document.getElementById("coverPhoto").click()
}}>
<h2>Selct a cover photo</h2>
<FaUpload/>
</div>
</div>
{/* Code block to display if the user have a cover photo */}
<img src={Globalconfig.userData.cover_picture_url} id="coverPic" style={{display: Globalconfig.userData.cover_picture_url === '' ? 'none' : 'block'}}></img>
{/*Profile Picture*/}
<img src={Globalconfig.userData.profile_picture} id="userProfilePicture"></img>
<h2 id="username">{Globalconfig.userData.first_name} {Globalconfig.userData.last_name}</h2>
{/* User Bio */}
<InputEditFirebase editIcon={<AiOutlineEdit/>} fireBaseObjKey="bio" fireBasePathToUpdate={"users/" Globalconfig.userData.UID} id="bio" textValue={Globalconfig.userData.bio} inputText={"Click to add bio"} uid={Globalconfig.userData.UID}>"{Globalconfig.userData.bio}"</InputEditFirebase>
</Container>
</div>
)
}
else{
return(
<div className="loader">
<div className="lds-circle"><div></div></div>
</div>
)
}
}
CodePudding user response:
React useEffect is causing infinite loop because you have given userData as an dependency in useEffect and you are also changing the value of userData inside useEffect. By fixing this it might fix our issue.