import { useEffect, useState } from "react";
export default function useFirestoreWatch(queryFactory, params) {
    const [docsList, updateList] = useState();
    useEffect(() => {
        const unsub = queryFactory(...params)((changes) => {
            updateList((prevList = []) => {
                for (let docChange of changes) {
                    if (docChange.type === undefined) {
                        const existing = prevList.find((f) => f.id === docChange.doc.id);
                        if (existing)
                            docChange.type = "modified";
                        else
                            docChange.type = "added";
                    }
                    switch (docChange.type) {
                        case 'added':
                            if (!prevList.find((f) => f.id === docChange.doc.id)) {
                                prevList.unshift(docChange.doc);
                            }
                            break;
                        case 'modified':
                            prevList = prevList.map((item) => {
                                if (item.id === docChange.doc.id)
                                    for (let key in docChange.doc) {
                                        item[key] = docChange.doc[key];
                                    }
                                return item;
                            });
                            break;
                        case 'removed':
                            prevList = prevList.filter((item) => item.id !== docChange.doc.id);
                            break;
                    }
                }
                return [...prevList];
            });
        });
        return unsub;
    }, params);
    return docsList;
}
//# sourceMappingURL=useFirestoreWatch.js.map