Home > Back-end >  Headless Wordpress Blog With Sveltekit Not Pulling Posts
Headless Wordpress Blog With Sveltekit Not Pulling Posts

Time:12-10

I'm trying to use sveltekit to build a blog using headless wordpress. I was following along with this app, but I think it's outdated.

I think I figured out routing, but on my blog page, I keep getting No Posts Found even though there are a couple posts on my local Wordpress install. I'm also using the WPGraphQL interface to make sure the query is pulling the data.

page.js

const query = `
    query getPosts {
      posts {
        nodes {
          databaseId
          uri
          title
          excerpt
          date
          featuredImage {
            node {
              sourceUrl
              altText
              mediaDetails {
                width
                height
              }
            }
          }
        }
      }
    }`;

export async function load({ fetch }) {
    const response = await fetch(import.meta.env.VITE_PUBLIC_WORDPRESS_API_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }, body: JSON.stringify({ query }),
    });

    if (response.ok) {
        const responseObj = await response.json();
        const posts = responseObj.data.posts.nodes;

        return {
            props: {
                posts
            }
        };
    }

    return {
        status: response.status, error: new Error(`Could not load ${url}`)
    };
}

page.svelte

<script>
    export let posts;
</script>

<h1>Blog</h1>
{#if posts}
    <ul>
        {#each posts as post}
            <li>
                {post.title}
            </li>
        {/each}
    </ul>
{:else}
    <p>No posts found.</p>
{/if}

<style>
    ul {
        list-style: none;
        padding: 0;
    }
    ul li   li {
        margin-top: 2rem;
    }
</style>

I am really new at this and I am not entirely sure what I'm doing wrong.

CodePudding user response:

The way the data is transferred is off. It should just be return { posts } and in the page all data from the load function is passed in a prop called data. So the posts would be in data.posts.

(For errors one should throw an error object constructed with the error function from @sveltejs/kit to show the error.svelte page.)

  • Related