I am trying the first project with Svelte and I have a situation like this:
I fetch a list of results from an API like here:
# Page with a list of items
<script context="module">
export const load = async ({ page, fetch }) => {
const res = await fetch(`url`);
const items = await res.json();
return {
props: {
items,
},
};
};
</script>
<script>
export let items;
</script>
{#each items.data as { id, item, href }}
<li>
<a href="/page/{href}">{ item }</a>
</li>
{/each}
I am trying to pass multiple parameters to the next (dynamic) route so that href is the slug and id is the id for fetching the item details from the API like here:
# Page with a single item
<script context="module">
export const load = async ({ page, fetch }) => {
const slug = page.params.slug; <-- I can get this
const res = await fetch(`url/${page.id}`); <-- but not this
const data = await res.json();
return {
props: {
data,
},
};
};
</script>
I apologise for my ignorance but I am really struggling and I do not know how to address this exactly. I would appreciate any hints.
There are two options for this
One is to have a second 'slug', this would mean you have a file structure like /page/[slug]/[id].svelte, in that case you can simply do const { slug, id } = page.params; and your anchor becomes <a href="/page/{href}/{id}">. This has the disadvantage that you still have to find a way to handle if people browse to /page/{href} without passing an id.
Another option is to pass the id as query parameter, here your anchor would be <a href="/page/{href}?id={id}"> the files are like what you have and you get the query parameter as follows const id = page.query.get('id'). Here you still have to handle if people come to this page without having an id, but in that case id will be undefined, so it's perhaps a touch easier to handle.