I'm working on a SvelteKit application where I need to fetch a list of posts data and avoid redundant API calls.
Route:
all-posts/+page.svelte
- Fetches the list of posts using
fetchAllPostsData()
- Fetches the list of posts using
Route:
post/[id]/[title]/+page.svelte
- Fetches the post data again using
fetchPostDataById(id)
- Displays the fetched data in the DOM
- Fetches the post data again using
The current implementation results in fetchAllPostsData()
being called, then fetchPostDataById(id)
being called again, which is inefficient. Here's the relevant code:
all-posts/+page.svelte
:
<script> import { onMount } from 'svelte'; import { fetchAllPostsData } from './fetch-post-data'; let postsDataArr = []; onMount(async () => { postsDataArr = await fetchAllPostsData(); });</script><section><ul> {#each postsDataArr as post}<li><a href={`/post/${post.id}/${post.title.replace(/[\s ]/g, '-')}`}>{post.title}</a></li> {/each}</ul></section>
post/[id]/[title]/+page.svelte
:
<script> import { onMount } from 'svelte'; import { page } from '$app/stores'; import { fetchPostDataById } from '../fetch-post-data'; let id; /** * @type {any} */ let data; $: id = $page.params.id; onMount(async () => { data = await fetchPostDataById(id); });</script><section> {#if data}<div><div>{@html data.html}</div></div> {/if}</section>
Additional Context:
I do not want to remove the fetchPostDataById(id)
functionality entirely, as it is essential for cases where users share a direct link to a post. In such scenarios, the post link should fetch the post data by ID to ensure the correct data is displayed even if the user accesses the post directly via URL.
Question:
How can I refactor my code to avoid calling the API twice? I want to fetch the list of posts once and use that data in both routes without redundant fetches.