Add way to not fetch data twice in `load` when provided `fetch` cannot be used
See original GitHub issueDescribe the problem
A lot of services provide SDKs used to simplify fetching data from their APIs, however a decent amount of them don’t provide an option for a custom fetch
function, so when you use that SDK in load()
the data will be fetched twice, both on the server and the client. A library I’m having trouble with is Ghost CMS’s SDK, and I remember having this issue with something else too but I can’t remember what it was.
Describe the proposed solution
A function passed to load could allow you to pass in a unique ID and a callback — it runs that callback, caches the result as JSON and returns it. Once the app loads on the client-side and runs load again this function could check the cache and return it. For example:
export async function load({ cache, params }) {
const post = cache(`post_${params.slug}`, async () => {
try {
return await someSdk.getPost(params.slug)
} catch {
return null
}
})
// Do other things in load
return { status: 200, props: { post } }
}
By caching I mean store the JSON string in the document the same way the custom fetch does - not sure if cache is the right term here
Alternatives considered
Using endpoints that run the SDK functions, but it’s a bit boilerplate and loses some type-safety
Importance
nice to have
Additional Information
No response
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:6 (1 by maintainers)
@Rich-Harris - Doesn’t Vercel use Serverless functions for each api call? This would dramatically increase the speed of your website. I think SvelteKit needs a transferState function so we have more control over what we can and can’t pass. Endpoints add more complexity. Plus, when you can avoid an endpoint, trying to pass a
fetch
function to apollo is a pain, Firebase doesn’t have one, and we have less control of our app. I also couldn’t figure out how to set-cookies to manually override this, as it seems impossible without an endpoint. I am a big fan of endpoints, but not with code that should not need the extra step. I personally prefer the returned value being set in the script, not the fetch value. You have way more control, and you don’t need an endpoint. I think NextJs’sgetServerSideProps
does this right.Either way, not a fan of the required endpoint in this use case.
J
Thanks @jdgamble555 I just found out about the new shadow endpoints and that seems to solve my use case perfectly.