Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How to avoid redundant API calls in SvelteKit when fetching post data

$
0
0

I'm working on a SvelteKit application where I need to fetch a list of posts data and avoid redundant API calls.

  1. Route:all-posts/+page.svelte

    • Fetches the list of posts using fetchAllPostsData()
  2. Route:post/[id]/[title]/+page.svelte

    • Fetches the post data again using fetchPostDataById(id)
    • Displays the fetched data in the DOM

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.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>