简体   繁体   中英

Custom hook getting undefined value then the correct object in react native?

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
}

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>
);

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