Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

feat: enhance useUpdateLink to optimistically update links

daniel31x13f3d30085de93
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index d75bf153..5affca7e 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -120,7 +120,7 @@ const RootComponent = ({
auth: MobileAuth;
}) => {
const { colorScheme } = useColorScheme();
- const updateLink = useUpdateLink(auth);
+ const updateLink = useUpdateLink({ auth, Alert });
const deleteLink = useDeleteLink({ auth, Alert });
const { tmp } = useTmpStore();
@@ -229,12 +229,12 @@ const RootComponent = ({
{tmp.link && tmp.user && (
<DropdownMenu.Item
key="pin-link"
- onSelect={async () => {
+ onSelect={() => {
const isAlreadyPinned =
tmp.link?.pinnedBy && tmp.link.pinnedBy[0]
? true
: false;
- await updateLink.mutateAsync({
+ updateLink.mutateAsync({
...(tmp.link as LinkIncludingShortenedCollectionAndTags),
pinnedBy: (isAlreadyPinned
? [{ id: undefined }]
diff --git a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
index 0d234479..8df91c89 100644
--- a/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
+++ b/apps/mobile/components/ActionSheets/EditLinkSheet.tsx
@@ -33,7 +33,7 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
const [link, setLink] = useState<
LinkIncludingShortenedCollectionAndTags | undefined
>(props.payload?.link);
- const editLink = useUpdateLink(auth);
+ const updateLink = useUpdateLink({ auth, Alert });
const router = useSheetRouter("edit-link-sheet");
const { colorScheme } = useColorScheme();
@@ -124,23 +124,15 @@ const Main = (props: SheetProps<"edit-link-sheet">) => {
/>
<Button
- onPress={() =>
- editLink.mutate(link as LinkIncludingShortenedCollectionAndTags, {
- onSuccess: () => {
- if (link && tmp.link)
- updateTmp({
- link,
- });
-
- SheetManager.hide("edit-link-sheet");
- },
- onError: (error) => {
- Alert.alert("Error", "There was an error editing the link.");
- console.error("Error editing link:", error);
- },
- })
- }
- isLoading={editLink.isPending}
+ onPress={() => {
+ updateLink.mutate(link as LinkIncludingShortenedCollectionAndTags);
+ if (link && tmp.link)
+ updateTmp({
+ link,
+ });
+ SheetManager.hide("edit-link-sheet");
+ }}
+ isLoading={updateLink.isPending}
variant="accent"
className="mb-2"
>
diff --git a/apps/mobile/components/LinkListing.tsx b/apps/mobile/components/LinkListing.tsx
index 9217810f..cbb150a7 100644
--- a/apps/mobile/components/LinkListing.tsx
+++ b/apps/mobile/components/LinkListing.tsx
@@ -40,7 +40,7 @@ type Props = {
const LinkListing = ({ link, dashboard }: Props) => {
const { auth } = useAuthStore();
const router = useRouter();
- const updateLink = useUpdateLink(auth);
+ const updateLink = useUpdateLink({ auth, Alert });
const { data: user } = useUser(auth);
const { colorScheme } = useColorScheme();
const { data } = useDataStore();
@@ -215,11 +215,11 @@ const LinkListing = ({ link, dashboard }: Props) => {
<ContextMenu.Item
key="pin-link"
- onSelect={async () => {
+ onSelect={() => {
const isAlreadyPinned =
link?.pinnedBy && link.pinnedBy[0] ? true : false;
- await updateLink.mutateAsync({
+ updateLink.mutateAsync({
...link,
pinnedBy: (isAlreadyPinned
? [{ id: undefined }]
diff --git a/apps/web/components/DragNDrop.tsx b/apps/web/components/DragNDrop.tsx
index 1b00612d..52759923 100644
--- a/apps/web/components/DragNDrop.tsx
+++ b/apps/web/components/DragNDrop.tsx
@@ -53,7 +53,7 @@ export default function DragNDrop({
onDragEnd: onDragEndProp,
}: DragNDropProps) {
const { t } = useTranslation();
- const updateLink = useUpdateLink();
+ const updateLink = useUpdateLink({ toast, t });
const pinLink = usePinLink();
const { data: user } = useUser();
const queryClient = useQueryClient();
@@ -104,25 +104,7 @@ export default function DragNDrop({
updatedLink: LinkIncludingShortenedCollectionAndTags,
opts?: { invalidateDashboardOnError?: boolean }
) => {
- const load = toast.loading(t("updating"));
- await updateLink.mutateAsync(updatedLink, {
- onSettled: async (_, error) => {
- toast.dismiss(load);
- if (error) {
- if (
- opts?.invalidateDashboardOnError &&
- typeof queryClient !== "undefined"
- ) {
- await queryClient.invalidateQueries({
- queryKey: ["dashboardData"],
- });
- }
- toast.error(error.message);
- } else {
- toast.success(t("updated"));
- }
- },
- });
+ updateLink.mutateAsync(updatedLink);
};
// DROP ON TAG
diff --git a/apps/web/components/LinkDetails.tsx b/apps/web/components/LinkDetails.tsx
index 1ca0126b..94f858e2 100644
--- a/apps/web/components/LinkDetails.tsx
+++ b/apps/web/components/LinkDetails.tsx
@@ -113,7 +113,7 @@ export default function LinkDetails({
);
};
- const updateLink = useUpdateLink();
+ const updateLink = useUpdateLink({ toast, t });
const updateFile = useUpdateFile();
const submit = async (e?: any) => {
@@ -126,21 +126,9 @@ export default function LinkDetails({
return;
}
- const load = toast.loading(t("updating"));
+ updateLink.mutateAsync(link);
- await updateLink.mutateAsync(link, {
- onSettled: (data, error) => {
- toast.dismiss(load);
-
- if (error) {
- toast.error(error.message);
- } else {
- toast.success(t("updated"));
- setMode && setMode("view");
- setLink(data);
- }
- },
- });
+ setMode && setMode("view");
};
const setCollection = (e: any) => {
diff --git a/apps/web/lib/client/pinLink.ts b/apps/web/lib/client/pinLink.ts
index bc530535..d83fa2ba 100644
--- a/apps/web/lib/client/pinLink.ts
+++ b/apps/web/lib/client/pinLink.ts
@@ -6,39 +6,21 @@ import { useUser } from "@linkwarden/router/user";
const usePinLink = () => {
const { t } = useTranslation();
- const updateLink = useUpdateLink();
+ const updateLink = useUpdateLink({ toast, t });
const { data: user } = useUser();
// Return a function that can be used to pin/unpin the link
const pinLink = async (link: LinkIncludingShortenedCollectionAndTags) => {
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0] ? true : false;
- const load = toast.loading(t("updating"));
-
try {
- await updateLink.mutateAsync(
- {
- ...link,
- pinnedBy: (isAlreadyPinned
- ? [{ id: undefined }]
- : [{ id: user?.id }]) as any,
- },
- {
- onSettled: (data, error) => {
- toast.dismiss(load);
-
- if (error) {
- toast.error(error.message);
- } else {
- toast.success(
- isAlreadyPinned ? t("link_unpinned") : t("link_pinned")
- );
- }
- },
- }
- );
+ updateLink.mutateAsync({
+ ...link,
+ pinnedBy: (isAlreadyPinned
+ ? [{ id: undefined }]
+ : [{ id: user?.id }]) as any,
+ });
} catch (e) {
- toast.dismiss(load);
console.error(e);
}
};
diff --git a/packages/router/collections.tsx b/packages/router/collections.tsx
index 90dd0504..b09e5674 100644
--- a/packages/router/collections.tsx
+++ b/packages/router/collections.tsx
@@ -177,7 +177,7 @@ const useDeleteCollection = ({
onError: (error, _variables, context) => {
if (toast && t) toast.error(t(error.message));
else if (Alert)
- Alert.alert("Error", "There was an error adding the link.");
+ Alert.alert("Error", "There was an error deleting the collection.");
if (!context) return;
diff --git a/packages/router/links.tsx b/packages/router/links.tsx
index c79375c4..32a86047 100644
--- a/packages/router/links.tsx
+++ b/packages/router/links.tsx
@@ -235,6 +235,123 @@ const removeLinkFromDashboardData = (oldData: any, linkId: number) => {
};
};
+const isLinkPinned = (link?: LinkIncludingShortenedCollectionAndTags) => {
+ return Boolean(link?.pinnedBy && link.pinnedBy.length > 0);
+};
+
+const findLinkInInfiniteData = (data: any, linkId: number) => {
+ if (!data?.pages?.length) return undefined;
+ for (const page of data.pages) {
+ const match = page?.links?.find((item: any) => item.id === linkId);
+ if (match) return match;
+ }
+ return undefined;
+};
+
+const findLinkInQueriesData = (
+ queries: [QueryKey, unknown][],
+ linkId: number
+) => {
+ for (const [, data] of queries ?? []) {
+ const match = findLinkInInfiniteData(data as any, linkId);
+ if (match) return match;
+ }
+ return undefined;
+};
+
+const findLinkInDashboardData = (data: any, linkId: number) => {
+ const match = data?.links?.find((item: any) => item.id === linkId);
+ if (match) return match;
+
+ const collectionLinks = data?.collectionLinks;
+ if (!collectionLinks) return undefined;
+
+ for (const links of Object.values(collectionLinks)) {
+ const collectionMatch = (links as any[])?.find(
+ (item: any) => item.id === linkId
+ );
+ if (collectionMatch) return collectionMatch;
+ }
+
+ return undefined;
+};
+
+const replaceLinkInInfiniteData = (
+ oldData: any,
+ link: LinkIncludingShortenedCollectionAndTags
+) => {
+ if (!oldData?.pages?.length) return oldData;
+
+ let updated = false;
+ const pages = oldData.pages.map((page: any) => {
+ const links = (page.links ?? []).map((item: any) => {
+ if (item.id === link.id) {
+ updated = true;
+ return link;
+ }
+ return item;
+ });
+ return { ...page, links };
+ });
+
+ if (!updated) return oldData;
+
+ return { ...oldData, pages };
+};
+
+const replaceLinkInDashboardData = (
+ oldData: any,
+ link: LinkIncludingShortenedCollectionAndTags
+) => {
+ if (!oldData) return oldData;
+
+ let updated = false;
+ const links = (oldData.links ?? []).map((item: any) => {
+ if (item.id === link.id) {
+ updated = true;
+ return link;
+ }
+ return item;
+ });
+
+ let collectionLinks = oldData.collectionLinks;
+ if (oldData.collectionLinks != null) {
+ const nextCollectionLinks = { ...oldData.collectionLinks };
+ for (const [collectionId, linksForCollection] of Object.entries(
+ nextCollectionLinks
+ )) {
+ const linkList = linksForCollection as any[];
+ if (!Array.isArray(linkList)) continue;
+ if (!linkList.some((item) => item.id === link.id)) continue;
+ updated = true;
+ nextCollectionLinks[Number(collectionId)] = linkList.map((item) =>
+ item.id === link.id ? link : item
+ );
+ }
+ collectionLinks = nextCollectionLinks;
+ }
+
+ if (!updated) return oldData;
+
+ return {
+ ...oldData,
+ links,
+ collectionLinks,
+ };
+};
+
+const applyPinnedDelta = (oldData: any, delta: number) => {
+ if (!oldData || !delta) return oldData;
+
+ return {
+ ...oldData,
+ numberOfPinnedLinks: Math.max(
+ 0,
+ (oldData.numberOfPinnedLinks ?? 0) + delta
+ ),
+ };
+};
+
const useAddLink = ({
auth,
Alert,
@@ -399,7 +516,17 @@ const useAddLink = ({
});
};
-const useUpdateLink = (auth?: MobileAuth) => {
+const useUpdateLink = ({
+ auth,
+ Alert,
+ toast,
+ t,
+}: {
+ auth?: MobileAuth;
+ Alert?: typeof Alert_;
+ toast?: typeof toaster;
+ t?: TFunction;
+}) => {
const queryClient = useQueryClient();
return useMutation({
@@ -424,6 +551,117 @@ const useUpdateLink = (auth?: MobileAuth) => {
return data.response;
},
+ onMutate: async (link) => {
+ const linkId = link.id;
+ if (linkId == null) {
+ return {};
+ }
+
+ await queryClient.cancelQueries({ queryKey: ["links"] });
+ await queryClient.cancelQueries({ queryKey: ["publicLinks"] });
+ await queryClient.cancelQueries({ queryKey: ["dashboardData"] });
+
+ const previousLinks = queryClient.getQueriesData({
+ queryKey: ["links"],
+ });
+ const previousPublicLinks = queryClient.getQueriesData({
+ queryKey: ["publicLinks"],
+ });
+ const previousDashboard = queryClient.getQueryData(["dashboardData"]);
+ const previousLinkQueries = queryClient.getQueriesData({
+ queryKey: ["link", linkId],
+ });
+
+ const cachedLink =
+ findLinkInQueriesData(previousLinks, linkId) ??
+ findLinkInDashboardData(previousDashboard, linkId);
+ const collections =
+ (queryClient.getQueryData(["collections"]) as any[]) ?? [];
+ const nextCollectionId =
+ link.collection?.id ?? cachedLink?.collection?.id;
+ const resolvedCollection =
+ nextCollectionId != null
+ ? collections.find((collection) => collection.id === nextCollectionId)
+ : undefined;
+ const optimisticCollection =
+ resolvedCollection ??
+ (link.collection?.id &&
+ cachedLink?.collection?.id === link.collection.id
+ ? { ...cachedLink.collection, ...link.collection }
+ : link.collection ?? cachedLink?.collection);
+
+ const previousPinned = isLinkPinned(cachedLink);
+ const nextPinned =
+ typeof link.pinnedBy === "undefined"
+ ? previousPinned
+ : isLinkPinned(link);
+ const pinnedDelta =
+ nextPinned === previousPinned ? 0 : nextPinned ? 1 : -1;
+
+ const optimisticLink = {
+ ...(cachedLink ?? {}),
+ ...link,
+ collection: optimisticCollection,
+ collectionId:
+ optimisticCollection?.id ??
+ link.collection?.id ??
+ cachedLink?.collectionId,
+ updatedAt: new Date().toISOString(),
+ } as LinkIncludingShortenedCollectionAndTags;
+
+ queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) =>
+ replaceLinkInInfiniteData(oldData, optimisticLink)
+ );
+
+ queryClient.setQueriesData(
+ { queryKey: ["publicLinks"] },
+ (oldData: any) => replaceLinkInInfiniteData(oldData, optimisticLink)
+ );
+
+ queryClient.setQueriesData(
+ { queryKey: ["link", linkId] },
+ () => optimisticLink
+ );
+
+ queryClient.setQueryData(["dashboardData"], (oldData: any) =>
+ applyPinnedDelta(
+ replaceLinkInDashboardData(oldData, optimisticLink),
+ pinnedDelta
+ )
+ );
+
+ return {
+ previousLinks,
+ previousPublicLinks,
+ previousDashboard,
+ previousLinkQueries,
+ };
+ },
+ onError: (error, _variables, context) => {
+ if (toast && t) toast.error(t(error.message));
+ else if (Alert)
+ Alert.alert("Error", "There was an error updating the link.");
+
+ if (!context) return;
+
+ context.previousLinks?.forEach(([queryKey, data]: [unknown, unknown]) => {
+ queryClient.setQueryData(queryKey as QueryKey, data);
+ });
+
+ context.previousPublicLinks?.forEach(
+ ([queryKey, data]: [unknown, unknown]) => {
+ queryClient.setQueryData(queryKey as QueryKey, data);
+ }
+ );
+
+ context.previousLinkQueries?.forEach(
+ ([queryKey, data]: [unknown, unknown]) => {
+ queryClient.setQueryData(queryKey as QueryKey, data);
+ }
+ );
+
+ queryClient.setQueryData(["dashboardData"], context.previousDashboard);
+ },
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ["links"] });
queryClient.invalidateQueries({ queryKey: ["link", data.id] });
@@ -503,7 +741,7 @@ const useDeleteLink = ({
onError: (error, _variables, context) => {
if (toast && t) toast.error(t(error.message));
else if (Alert)
- Alert.alert("Error", "There was an error adding the link.");
+ Alert.alert("Error", "There was an error deleting the link.");
if (!context) return;