Неправильный ввод React Hook с Firestore - PullRequest
0 голосов
/ 23 сентября 2019

У меня есть пользовательский хук для запроса определенной коллекции / документа Firebase Firestore.

import { useContext, useEffect, useState } from 'react';

import { FirebaseContext } from 'providers/Firebase/FirebaseContextProvider';

const useFireStore = (
  collection: string,
  doc: string,
  loadingDelay: number = 0,
) => {
  const { firestore } = useContext(FirebaseContext);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [document, setDocument] = useState<
    firebase.firestore.DocumentData | undefined
  >();

  useEffect(() => {
    setLoading(true);
    setDocument(undefined);
    const docRef = firestore.collection(collection).doc(doc);
    docRef
      .get()
      .then(doc => {
        setDocument(doc.data());
        setTimeout(() => {
          setLoading(false);
        }, loadingDelay);
      })
      .catch(e => {
        setError(e);
        setLoading(false);
      });
  }, [collection, loadingDelay, doc, firestore]);

  return [document, loading, error];
};

export default useFireStore;

Я использую его следующим образом:

const [details, loading, error] = useFireStore('listDetails', `${id}`, 300);

Когда я наводю курсор мыши на document вconst [document, setDocument] = useState в ловушке, я вижу, что тип document будет:

const document: firebase.firestore.DocumentData | undefined

Однако, когда я наведу курсор мыши на document в const [details, loading, error] = ... в компоненте,Я вижу возможные типы:

const details: boolean | firebase.firestore.DocumentData | null | undefined

Откуда это возможно boolean или null откуда?

1 Ответ

0 голосов
/ 24 сентября 2019

Я решил это, набрав код возврата useFireStore, например:

const useFireStore = (
  collection: string,
  doc: string,
  loadingDelay: number = 0,
): [firebase.firestore.DocumentData | undefined, boolean, Error | null] => {
...
}
...