mirror of
https://github.com/docmost/docmost.git
synced 2025-11-12 19:22:39 +10:00
* sync node deletion * tree sync improvements * fix cache bug * fix debounced page title * fix
58 lines
1.8 KiB
TypeScript
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]);
|
|
};
|