'Firebase TypeError: Cannot read properties of null (reading 'indexOf')

When I console.log(docSnap) I'm getting a firebase error, see in the below image. I have tried all the solutions but none of them worked.

Firebase error

useEffect(() => {
        if (folderId === null) {
            dispatch({
                type: "UPDATE_FOLDER",
                payload: { folder: ROOT_FOLDER }
            })
        }
        // otherwise fetch from database

        const getdocSnap = async () => {
            const docRef = doc(db, "folders", folderId);
            return await getDoc(docRef);
        }
        const docSnap = getdocSnap();
        console.log(docSnap);

        if (docSnap.exists()) {
            dispatch({
                type: "UPDATE_FOLDER",
                payload: { folder: { id: docSnap.id, ...docSnap.data() } }
            })
        } else {

            console.log("No such document!");
            dispatch({
                type: "UPDATE_FOLDER",
                payload: { folder: ROOT_FOLDER }
            })
        }

    }, [folderId])


Solution 1:[1]

How the problem solved ?

Ans: Created an async function callFunc & pasted all my logic inside it & called it.

Try the code below

useEffect(() => {
        if (folderId === null) {
            return dispatch({
                type: "UPDATE_FOLDER",
                payload: { folder: ROOT_FOLDER }
            })
        }
        // otherwise fetch from database
        const callFunc = async () => {
            const docRef = doc(db, "folders", folderId);
            const docSnap = await getDoc(docRef);

            if (docSnap.exists()) {
                dispatch({
                    type: "UPDATE_FOLDER",
                    payload: { folder: { id: docSnap.id, ...docSnap.data() } }
                })
            } else {

                console.log("No such document!");
                dispatch({
                    type: "UPDATE_FOLDER",
                    payload: { folder: ROOT_FOLDER }
                })
            }
        }

        callFunc();

    }, [folderId])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gulshan Aggarwal