Guarantee the data retrieved from Firebase is not NULL

Viewed 29

I met this error when I tried to consume some data:

Unhandled Rejection (TypeError): undefined is not an object (evaluating 'snapshot.docs[0].data')

I think it's due to the emptiness of the dataset although I'm the admin of my org's Firebase account. So to be more robust, what can I do to my code? For example, how can I set the default value (i.e. empty string "") if value undefined is detected?

import { AuthContext } from "./Auth/Auth";

function Transfer() {
    const [type, setType] = useState([]);
    const {currentUser} = useContext(AuthContext);

    useEffect(() => {
        if(currentUser){
            firebaseApp.firestore()
            .collection("User")
            .where("userEmail", "==", currentUser.email)
            .get()
            .then(snapshot => 
                setType(snapshot.docs[0].data().userType)
            );
        }
        

    }, [type])
}
1 Answers

try this:

const userInfo = snapshot.docs[0].data()
setType(userInfo?.userType || "")
Related