How dependent fetching works
masterYou can perform dependent fetching by passing a function as the key to useSWR. When the dependency (e.g., a previous request's data) is not yet available, the function can throw an error or return a value that causes the hook to wait. Once the dependency is resolved, the function returns the new key, and the hook fetches the dependent data.
Example:
<script>
import { useSWR } from "sswr";
// Primary request
const { data: post } = useSWR("https://jsonplaceholder.typicode.com/posts/1");
// Dependent request: the key is a function that depends on $post
$: ({ data: user } = useSWR(
() => `https://jsonplaceholder.typicode.com/users/${$post.userId}`
));
</script>
{#if $post}
<div>{$post.title}</div>
{/if}
{#if $user}
<div>{$user.name}</div>
{/if}<script>
import { useSWR } from "sswr";
const { data: post } = useSWR("https://jsonplaceholder.typicode.com/posts/1");
$: ({ data: user } = useSWR(
() => `https://jsonplaceholder.typicode.com/users/${$post.userId}`
));
</script>
{#if $post}
<div>{$post.title}</div>
{/if}
{#if $user}
<div>{$user.name}</div>
{/if}