Ricardo de Paula
Ricardo de Paula

Reputation: 632

Is there a way to make dynamically queries using SvelteKit load function?

I am stuck trying to make Strapi's filter parameter dynamic in SvelteKit.

Using insomnia, the backend, filters posts based on the parameter, as usual.

enter image description here

I am trying to use the page object from the svelte load function. Where it has the {query} object which is an instance of the URLSearchParams interface, according to the documentation.

I created the "search" page to show the filter results:

export async function load({ page, fetch }) {
        const term = page.query.term;
        const url = 'http://localhost:1337/posts';
        const data = await fetch(`${url}?categories.name_contains=${term}`);

        if (data.ok) {
            return { props: { posts: await data.json() } };
        }

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

On that same page ("search") I make an import of a component called PostList, which lists the posts. I pass the props posts for the component.

 <div class="post-card">
        {#each posts as post (post.id)}
            <PostList {post} />
        {/each}
 </div>

Inside the PostList component, I try to do the filter using a url containing the parameter. The code is in {#each post.categories as category (category.id)} ...

PostList component:

<script>
    // Script will be here
    export let post;
</script>

<!--HTML here-->
<div>
    <img src={post.image.formats.medium.url} alt={post.title} />
    <div class="mobile-display">
        <h3>
            <a href={post.slug}>
                {post.title}
            </a>
        </h3>
        <p class="fade-truncate">
            {post.description}
        </p>
        {#each post.categories as category (category.id)}
            <a href={`/search?term=${category.name}`}>
                {category.name}
            </a>
        {/each}
    </div>
</div>

I am pretty sure that the problem is in the load function, which is not updating the value ${term} in the function.

Thank you in advance for any assistance.

Upvotes: 1

Views: 1305

Answers (1)

Mohammad Saiful
Mohammad Saiful

Reputation: 386


export async function load({ page, fetch }) {
        const term = page.query.get('term');
        const url = 'http://localhost:1337/posts';
        const data = await fetch(`${url}?categories.name_contains=${term}`);

        if (data.ok) {
            return { props: { posts: await data.json() } };
        }

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

Try like this

Upvotes: 2

Related Questions