Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(dashboard): implement optimistic updates for dashboard edits

Bill Yang05ee87a79590
diff --git a/client/src/api/analytics/hooks/useDashboards.ts b/client/src/api/analytics/hooks/useDashboards.ts
index 786940089..36c6f2f4f 100644
--- a/client/src/api/analytics/hooks/useDashboards.ts
+++ b/client/src/api/analytics/hooks/useDashboards.ts
@@ -49,7 +49,49 @@ export function useUpdateDashboard() {
name?: string;
config?: DashboardConfig;
}) => updateDashboard(siteId, dashboardId, { name, config }),
- onSuccess: (_, variables) => {
+ // Write the edit into the cache before the round trip. Without this the
+ // editor drops its working copy on save and falls back to the cached
+ // dashboard, which is still the pre-save version until the refetch lands.
+ onMutate: async ({ siteId, dashboardId, name, config }) => {
+ const detailKey = ["get-dashboard", siteId, dashboardId];
+ const listKey = ["get-dashboards", siteId];
+ // In-flight refetches would otherwise resolve over the optimistic value.
+ await Promise.all([
+ queryClient.cancelQueries({ queryKey: detailKey }),
+ queryClient.cancelQueries({ queryKey: listKey }),
+ ]);
+
+ const previousDetail = queryClient.getQueryData<Dashboard>(detailKey);
+ const previousList = queryClient.getQueryData<Dashboard[]>(listKey);
+ const applyEdit = (dashboard: Dashboard): Dashboard => ({
+ ...dashboard,
+ name: name ?? dashboard.name,
+ config: config ?? dashboard.config,
+ updatedAt: new Date().toISOString(),
+ });
+
+ if (previousDetail) {
+ queryClient.setQueryData<Dashboard>(detailKey, applyEdit(previousDetail));
+ }
+ if (previousList) {
+ queryClient.setQueryData<Dashboard[]>(
+ listKey,
+ previousList.map(dashboard => (dashboard.dashboardId === dashboardId ? applyEdit(dashboard) : dashboard))
+ );
+ }
+
+ return { detailKey, listKey, previousDetail, previousList };
+ },
+ onError: (_error, _variables, context) => {
+ if (!context) return;
+ if (context.previousDetail) {
+ queryClient.setQueryData(context.detailKey, context.previousDetail);
+ }
+ if (context.previousList) {
+ queryClient.setQueryData(context.listKey, context.previousList);
+ }
+ },
+ onSettled: (_data, _error, variables) => {
queryClient.invalidateQueries({ queryKey: ["get-dashboards", variables.siteId] });
queryClient.invalidateQueries({ queryKey: ["get-dashboard", variables.siteId, variables.dashboardId] });
},
diff --git a/client/src/app/[site]/dashboards/[dashboardId]/page.tsx b/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
index a88aa582b..f77bda14d 100644
--- a/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
+++ b/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
@@ -200,20 +200,28 @@ export default function DashboardDetailPage() {
[guardedRun, router, siteId]
);
- const handleSave = useCallback(async () => {
- try {
- await updateDashboard.mutateAsync({
- siteId,
- dashboardId,
- name: workingName,
- config: { cards: workingCards },
- });
- toast.success("Dashboard saved");
- resetWorkingCopy();
- setEditMode(false);
- } catch (error) {
- toast.error(error instanceof Error ? error.message : "Couldn't save dashboard");
- }
+ // The mutation writes the edit into the query cache up front, so leave edit
+ // mode right away rather than holding the user on a spinner. If the request
+ // fails the cache rolls back and we put the working copy (and edit mode) back
+ // exactly as it was, so nothing typed is lost.
+ const handleSave = useCallback(() => {
+ const savedName = workingName;
+ const savedCards = workingCards;
+ resetWorkingCopy();
+ setEditMode(false);
+ updateDashboard.mutate(
+ { siteId, dashboardId, name: savedName, config: { cards: savedCards } },
+ {
+ onSuccess: () => toast.success("Dashboard saved"),
+ onError: error => {
+ setName(savedName);
+ setCards(savedCards);
+ setDirty(true);
+ setEditMode(true);
+ toast.error(error instanceof Error ? error.message : "Couldn't save dashboard");
+ },
+ }
+ );
}, [updateDashboard, siteId, dashboardId, workingName, workingCards, resetWorkingCopy]);
// Warn before a full reload / tab close with unsaved edits.
@@ -280,14 +288,14 @@ export default function DashboardDetailPage() {
const handler = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") {
event.preventDefault();
- if (dirty && !updateDashboard.isPending) handleSave();
+ if (dirty) handleSave();
} else if (event.key === "Escape" && !confirmExit && !editingCardId && !addingCard) {
handleCancel();
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
- }, [editMode, dirty, confirmExit, editingCardId, addingCard, updateDashboard.isPending, handleSave, handleCancel]);
+ }, [editMode, dirty, confirmExit, editingCardId, addingCard, handleSave, handleCancel]);
if (isLoading) {
return (
@@ -380,12 +388,8 @@ export default function DashboardDetailPage() {
<Button variant="ghost" size="sm" onClick={handleCancel}>
Cancel
</Button>
- <Button size="sm" onClick={handleSave} disabled={!dirty || updateDashboard.isPending}>
- {updateDashboard.isPending ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Check className="h-4 w-4" />
- )}
+ <Button size="sm" onClick={handleSave} disabled={!dirty}>
+ <Check className="h-4 w-4" />
Save
</Button>
</>