I'm trying to build a code that, depending on the result coming from the Hook, redirects to a different page.
So my hook uses the code below:
import { useEffect, useState } from "react"
import { database } from "../../services/firebase"
type UserDetails = {
id: string,
userID: string,
userName: string,
userEmail: string,
userAvatar: string,
userDescription: string,
userSkills: string,
userPhone: string,
userTitle: string,
userInterests: string
}
export function useGetUserProfile(userid: string | undefined){
const [ userDef, setUserDef ] = useState<UserDetails>()
const [ loading, setLoading ] = useState<boolean>(true)
useEffect(()=>{
const userRef = database.ref(`users/${userid}`);
userRef.on('value', userInfo =>{
const databaseUser = userInfo.val();
const userDetails: UserDetails = {
id: databaseUser.key,
userID: databaseUser.userID,
userName: databaseUser.userName,
userEmail: databaseUser.userEmail,
userAvatar: databaseUser.userAvatar,
userDescription: databaseUser.userDescription,
userSkills: databaseUser.userSkills,
userPhone: databaseUser.userPhone,
userTitle: databaseUser.userTitle,
userInterests: databaseUser.userInterests
}
setUserDef(userDetails);
setLoading(false);
})
},[userid])
return{userDef, loading}
}
And here is my page function:
const [ userId, setUserID ] = useState<string | undefined>("")
const { userDef, loading } = useGetUserProfile(userId)
async function handleAuthGoogle(){
if(!user){
await singIngWithGoogle();
}
if(!loading){
await setUserID(user?.id)
if(userDef != undefined){
navigate('/home');
}else{
navigate(`/Profile/Editar/${userId}`)
}
}
}
The function completes before the hook loads. My question is, how do I code it in order to wait the hook completes loading to then run the function? I tried using while, but didn't work well.