0

Hello so am trying to make a custom hook where i get my user object from database and using it however my console log shows the the object is undefined shortly after object appears and this effect other function relying on it they only capture the first state and gives an error how can i fix that here is my code for the hook:-

import { useState, useEffect } from 'react'
import { storage, auth, database } from '../api/auth';



export default function useUser() {
    const [user, setUser] = useState()
    const userId = auth.currentUser.uid;

    useEffect(() => {
        getCurrentUser();

    }, [])


    const getCurrentUser = () => {
        database.ref("users/" + userId).orderByChild('name').once("value").then(snapshot => {
            setUser(snapshot.val())
        })
    }

    return user
}

1 Answer 1

1

First of all you can assign default value to userObject.

const [user, setUser] = useState(null);

After place where you use useUser hook you can make a check is it null or not.

const user = useUser();


if (!user) {
    return <Text>Loading...</Text>;
}

return(
    <Text>{user.name}</Text>
);
Sign up to request clarification or add additional context in comments.

4 Comments

i did what you said the initialize to null and called the hook in my other components however it gives user = null and then the user=object?
Yes. First you need to fetch the user. Until that moment while user=null you can show the spinner, loading message or return null. When you get the user(user=object), you just render.
what about other function that need to compute the user for example i have a function needs user._id how do i make them wait for user to get updated and not give me an error user is null?
you just wrap them inside useEffect and provide user as a dependency. Inside useEffect before running your function you can check is user null or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.