export function withCollectionState()

in src/components/Firestore/Collection.tsx [63:123]


export function withCollectionState(
  Presentation: React.ComponentType<CollectionPresentationProps>
): React.ComponentType<Props> {
  return ({ collection }) => {
    const [newDocumentId, setNewDocumentId] = useState<string>();
    const collectionFilter = useCollectionFilter(collection.path);
    const filteredCollection = applyCollectionFilter(
      collection,
      collectionFilter
    );
    const collectionSnapshot = useFirestoreCollection<unknown>(
      filteredCollection,
      {
        suspense: true,
      }
    );
    const history = useHistory();

    const { url } = useRouteMatch()!;

    const missingDocs = useMissingDocuments(collection);

    const docs = collectionSnapshot.data.docs.length
      ? collectionSnapshot.data.docs
      : NO_DOCS;
    const redirectIfAutoSelectable = useAutoSelect(docs);

    const addDocument = async (value: AddDocumentDialogValue | null) => {
      if (value && value.id) {
        await collection.doc(value.id).set(value.data);
        setNewDocumentId(value.id);
      }
    };

    useEffect(() => {
      if (newDocumentId) {
        history.push(`${url}/${encodeURIComponent(newDocumentId)}`);
        setNewDocumentId('');
      }
    }, [history, url, newDocumentId, setNewDocumentId]);

    if (newDocumentId) {
      return null;
    }

    if (redirectIfAutoSelectable) {
      return <>{redirectIfAutoSelectable}</>;
    }

    return (
      <Presentation
        collection={collection}
        collectionFilter={collectionFilter}
        addDocument={addDocument}
        docs={docs}
        missingDocs={missingDocs}
        url={url}
      />
    );
  };
}