The patterns detailed in the last couple of steps can be repeated now for getting data from the GraphQL endpoint.
An alternative way to retrieve the data is detailed in the SvelteKit endpoints section you can tackle outside of the workshop.
In this section we’ll create a /posts
route in the project that will list all the posts from the endpoint, much like on the index page.
Create the posts folder and the .js
and .svelte
files for the route:
mkdir src/routes/posts
touch src/routes/posts/{+page.js,+page.svelte}
In the +page.js
file, where the data will be retreived in a load
function it will be a similar pattern to the index page:
import { client } from '$lib/graphql/graphql-client';
import { getAllPosts } from '$lib/graphql/graphql-queries';
/** @type {import('./$types').PageLoad} */
export const load = async () => {
const { posts } = await client.request(getAllPosts);
return {
posts
};
};
Then in the +page.svelte
file we can use the data passed to it from the +page.js
file:
<script>
import PostCard from '$components/post-card.svelte';
/**
* @type {import('./$types').PageData}
*/
export let data;
let { posts } = data;
</script>
<div class="prose prose-xl mb-10">
<h1>Posts</h1>
<p>This is all of posts I've written about building with SvelteKit and GraphQL.</p>
</div>
{#each posts as post}
<PostCard {post} />
{/each}