I am super excited about the Solidjs, the 🚀 speed JavaScript framework. In this I will show you how to read data from a
Graphql endpoint.There are libraries such as Apollo which used a React specific approach, so I decide to use another library called URQL
How to ?
For reading async data Solidjs provides us Resources, which is a signal. We can combine URQL client within the createResource command with an arrow function.
Install the dependencies
We need two dependencies for using graphql namely, graphgql and @urql/core
yarn add graphql @urql/core
URQL Client
In this example I used a mock graphql API,also stored the URL in .env (which require vite configuration) file. Let's initialize out API with url
import { createClient } from "@urql/core";
const client = createClient({
url: API_GQL,
});
Create Resource and fetch
We can either create another function for fetching data as in REST API fetcher or simplify go with an arrow function as follow.
const [posts]= createResource(()=>client.query(`
query {
posts {
title
id
excerpt
featured_image
}
}
`).toPromise().then(data=>{
return data.data.posts
}));
Rendering the data
We can use Show and For components to render the list. Show let's allow check the data is available for render, it may contain null or undefined.
<Show when={posts()}><For each={posts()}>{(post) => <PostCard post={post} />}</For>
</Show>
Read More GQL posts
0 comments:
Post a Comment