From 68db7c380e3f240f9b96f2b13f2fd956af9c223e Mon Sep 17 00:00:00 2001 From: Alem Tuzlak Date: Tue, 21 Jan 2025 14:15:54 +0100 Subject: [PATCH] Added createClientLoaderCache utility --- README.md | 14 ++++++++++++++ src/index.tsx | 15 ++++++++++++++- test-apps/testing-app/app/routes/_index.tsx | 3 ++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dfb43e8..da434c5 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,20 @@ clientLoader.hydrate = true; ``` +### createClientLoaderCache + +Creates everything needed to cache the data via clientLoader, behind the scenes creates the clientLoader object with the correct hydrate flag and the adapter. + +```tsx +import { createClientLoaderCache, cacheClientLoader } from "remix-client-cache"; + +export const clientLoader = createClientLoaderCache(); + +// above is equivalent to: +export const clientLoader = (args: ClientLoaderFunctionArgs) => cacheClientLoader(args); +clientLoader.hydrate = true; +``` + ### decacheClientLoader Used to remove the data that is piped from the loader to your component using the `clientLoader` export. diff --git a/src/index.tsx b/src/index.tsx index 0ae99d0..adb89f7 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -79,13 +79,19 @@ export const decacheClientLoader = async ( return data; }; +type CacheClientLoaderArgs = { + type?: "swr" | "normal"; + key?: string; + adapter?: CacheAdapter; +}; + export const cacheClientLoader = async ( { request, serverLoader }: ClientLoaderFunctionArgs, { type = "swr", key = constructKey(request), adapter = cache, - }: { type?: "swr" | "normal"; key?: string; adapter?: CacheAdapter } = { + }: CacheClientLoaderArgs = { type: "swr", key: constructKey(request), adapter: cache, @@ -119,6 +125,13 @@ export const cacheClientLoader = async ( }; }; +export const createClientLoaderCache = (props?: CacheClientLoaderArgs) => { + const clientLoader = (args: ClientLoaderFunctionArgs) => + cacheClientLoader(args, props); + clientLoader.hydrate = true; + return clientLoader; +}; + export function useCachedLoaderData( { adapter = cache }: { adapter?: CacheAdapter } = { adapter: cache }, ) { diff --git a/test-apps/testing-app/app/routes/_index.tsx b/test-apps/testing-app/app/routes/_index.tsx index fbebf98..8eaddbb 100644 --- a/test-apps/testing-app/app/routes/_index.tsx +++ b/test-apps/testing-app/app/routes/_index.tsx @@ -7,6 +7,7 @@ import { import type { MetaFunction } from "react-router"; import { cacheClientLoader, + createClientLoaderCache, decacheClientLoader, useCachedLoaderData, } from "remix-client-cache"; @@ -25,7 +26,7 @@ export const loader = async () => { return { user: { description: Math.random() } }; }; -export const clientLoader = cacheClientLoader; +export const clientLoader = createClientLoaderCache(); clientLoader.hydrate = true; export const clientAction = decacheClientLoader;