Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Headless WordPress Blog With Sveltekit Not Pulling Posts

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading