Files
docmost/apps/client/src/features/websocket/use-query-subscription.ts
Philip Okugbe 978fadd6b9 fix: improve sidebar page tree syncing (#407)
* sync node deletion

* tree sync improvements

* fix cache bug

* fix debounced page title

* fix
2024-10-26 15:48:40 +01:00

58 lines
1.8 KiB
TypeScript

import React from "react";
import { socketAtom } from "@/features/websocket/atoms/socket-atom.ts";
import { useAtom } from "jotai";
import { useQueryClient } from "@tanstack/react-query";
import { WebSocketEvent } from "@/features/websocket/types";
export const useQuerySubscription = () => {
const queryClient = useQueryClient();
const [socket] = useAtom(socketAtom);
React.useEffect(() => {
socket?.on("message", (event) => {
const data: WebSocketEvent = event;
let entity = null;
let queryKeyId = null;
switch (data.operation) {
case "invalidate":
queryClient.invalidateQueries({
queryKey: [...data.entity, data.id].filter(Boolean),
});
break;
case "updateOne":
entity = data.entity[0];
if (entity === "pages") {
// we have to do this because the usePageQuery cache key is the slugId.
queryKeyId = data.payload.slugId;
} else {
queryKeyId = data.id;
}
// only update if data was already in cache
if(queryClient.getQueryData([...data.entity, queryKeyId])){
queryClient.setQueryData([...data.entity, queryKeyId], {
...queryClient.getQueryData([...data.entity, queryKeyId]),
...data.payload,
});
}
/*
queryClient.setQueriesData(
{ queryKey: [data.entity, data.id] },
(oldData: any) => {
const update = (entity: Record<string, unknown>) =>
entity.id === data.id ? { ...entity, ...data.payload } : entity;
return Array.isArray(oldData)
? oldData.map(update)
: update(oldData as Record<string, unknown>);
},
);
*/
break;
}
});
}, [queryClient, socket]);
};