Created
February 5, 2025 12:35
-
-
Save Sama-004/ed21322ccb190aeaff4bb5ed188a3637 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
export async function loader({ request }: LoaderFunctionArgs) { | |
const emails = db query 1 (without await) | |
const folders = db query 2 (without await) | |
return defer({ | |
emails, | |
folders, | |
}); | |
} | |
let cache = { | |
data: null, | |
promise: null as Promise<any> | null, | |
}; | |
export async function clientLoader({ serverLoader }) { | |
const freshDataPromise = serverLoader().then((newData) => ({ | |
emails: newData.emails, | |
folders: newData.folders, | |
})); | |
if (cache.data) { | |
console.log('returning cached data while revalidating'); | |
cache.promise = freshDataPromise; | |
// Update cache when the fresh data arrives | |
freshDataPromise | |
.then((newData) => { | |
cache.data = newData; | |
cache.promise = null; | |
console.log('cache updated in background'); | |
}) | |
.catch((error) => { | |
console.error('Failed to update cache:', error); | |
cache.promise = null; | |
}); | |
return cache.data; | |
} | |
if (cache.promise) { | |
const data = await cache.promise; | |
cache.data = data; | |
cache.promise = null; | |
return data; | |
} | |
// No cache and no pending promise, wait for fresh data | |
const freshData = await freshDataPromise; | |
cache.data = freshData; | |
return freshData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment