resize
This commit is contained in:
66
apps/web/src/hooks/use-entry-resized-mutation.ts
Normal file
66
apps/web/src/hooks/use-entry-resized-mutation.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type { NormalizedTimeline } from "@/functions/get-timeline";
|
||||
import { updateTimelineItem } from "@/functions/update-timeline-item";
|
||||
|
||||
type EntryResizedVars = {
|
||||
entryId: string;
|
||||
newStart: string;
|
||||
newEnd: string | null;
|
||||
groupId: string;
|
||||
lane: number;
|
||||
};
|
||||
|
||||
export function useEntryResizedMutation(timelineId: string) {
|
||||
const queryClient = useQueryClient();
|
||||
const queryKey = ["timeline", timelineId];
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (vars: EntryResizedVars) =>
|
||||
updateTimelineItem({
|
||||
data: {
|
||||
id: vars.entryId,
|
||||
start: vars.newStart,
|
||||
end: vars.newEnd,
|
||||
timelineGroupId: vars.groupId,
|
||||
lane: vars.lane,
|
||||
},
|
||||
}),
|
||||
|
||||
onMutate: async (vars) => {
|
||||
// Cancel in-flight fetches so they don't overwrite our optimistic update
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
const previous = queryClient.getQueryData<NormalizedTimeline>(queryKey);
|
||||
|
||||
queryClient.setQueryData<NormalizedTimeline>(queryKey, (old) => {
|
||||
if (!old) return old;
|
||||
|
||||
return {
|
||||
...old,
|
||||
items: {
|
||||
...old.items,
|
||||
[vars.entryId]: {
|
||||
...old.items[vars.entryId],
|
||||
start: new Date(vars.newStart),
|
||||
end: vars.newEnd ? new Date(vars.newEnd) : null,
|
||||
lane: vars.lane,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return { previous };
|
||||
},
|
||||
|
||||
onError: (_err, _vars, context) => {
|
||||
// Roll back to the previous cache state on server error
|
||||
if (context?.previous) {
|
||||
queryClient.setQueryData(queryKey, context.previous);
|
||||
}
|
||||
},
|
||||
|
||||
onSettled: () => {
|
||||
// Re-fetch from server to ensure consistency
|
||||
queryClient.invalidateQueries({ queryKey });
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user