WatermelonDB icon indicating copy to clipboard operation
WatermelonDB copied to clipboard

experimentalSubscribe with useSyncExternalStore doesn't re render on update

Open krudos opened this issue 2 years ago • 0 comments

i created a helper hook to use a table. i working ok for everything but except the update.

any reason why the experimentalSubscribe is not trigger when an update is made? ` const useTable = <T extends Model>(tableName: string) => { const collection = database.get<T>(tableName); const [data, setData] = useState<T[]>([]);

const subscribe = useMemo(() => {
    return (notify: () => void) => {
        const unsubscribe = collection
            .query()
            .experimentalSubscribe((records: T[]) => {
                setData(records);
                notify();
            });

        return unsubscribe;
    };
}, []);

const create = (recordBuilder: (record: T) => void) =>
    database.write(async () => collection.create(recordBuilder));

const update = (id: string, recordBuilder: (record: T) => void) =>
    database.write(async () =>
        collection
            .find(id)
            .then(x => x.update(recordBuilder))
    );

const remove = (id: string) =>
    database.write(async () =>
        collection.query(Q.where('id', id)).destroyAllPermanently(),
    );

const truncate = () =>
    database.write(async () => collection.query().destroyAllPermanently());

const batchInsert = (records: ((record: T) => void)[]) =>
    database.write(async () => {
        const rows = records.map(record =>
            collection.prepareCreate(record),
        );

        await database.batch(...rows);
    });

const storeData = useSyncExternalStore<T[]>(subscribe, () => data);

return {
    database,
    collection,
    data: storeData,
    create,
    remove,
    update,
    truncate,
    batchInsert,
};

};`

krudos avatar Nov 30 '23 13:11 krudos