Last active
April 21, 2025 19:01
-
-
Save sethdavis512/4eef7505cb77e35e19191dc09bc992c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FlatCache } from 'flat-cache'; | |
export const cache = new FlatCache(); | |
// =========== | |
let isInitialRequest = true; | |
// Utility function to generate a unique cache key | |
function generateKey(request: Request): string { | |
return `${request.method}:${request.url}`; | |
} | |
export async function clientLoader({ | |
request, | |
serverLoader | |
}: Route.ClientLoaderArgs) { | |
const cacheKey = generateKey(request); // Generate a unique key for the request | |
if (isInitialRequest) { | |
isInitialRequest = false; | |
const serverData = await serverLoader(); | |
cache.setKey(cacheKey, serverData); // Cache the server data | |
cache.save(); // Persist the cache to disk | |
return serverData; | |
} | |
const cachedData = cache.getKey<typeof serverData>(cacheKey); // Retrieve cached data | |
if (cachedData) { | |
return cachedData; // Return cached data if available | |
} | |
const serverData = await serverLoader(); | |
cache.setKey(cacheKey, serverData); // Cache the new server data | |
cache.save(); // Persist the cache to disk | |
return serverData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment