Next.jsでエラーFirebaseError: Function doc() cannot be called with an empty path.

https://zenn.dev/dala/books/nextjs-firebase-service

こちらのzenn.devのnext.js入門書を実装中に発生したエラー。

FirebaseError: Function doc() cannot be called with an empty path.

エラーの内容の意味

firestoreのdocというパッケージに渡した引数がemptyつまり空だよ

docの中身を見ればいいわけです。

僕のケースでいえば以下のコードのquery.uidの部分です。

firebaseのfirestoreから取得したuidが空だったことが原因でした。

  const [user, setUser] = useState<User>(null)
  const router = useRouter()
  const query = router.query as Query

  useEffect(() => {

    async function loadUser() {
      const db = getFirestore()
      const ref = doc(collection(db, 'users'), query.uid)
      const userDoc = await getDoc(ref)

      if (!userDoc.exists()) {
        return
      }

      const gotUser = userDoc.data() as User
      gotUser.uid = userDoc.id
      setUser(gotUser)
    }
    loadUser()
  }, [query.uid])

ブラウザ上でURLのクエリ文字から取得する文字列であるquery.uidを取得する前にuseEffectが実行されるため、queryがnullだったために発生していたエラーでした。

 

if (query.uid == undefined){
return
}

async functionの上にこれを入れてあげて解決しました。