UI developer tutorials and guides

Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Friday, June 24, 2022

How to apply refetch logic in Solidjs

 In Reactjs libraries such ReactQuery make API fetching so simple and fast. Solidjs also come with powerful tools. 

We have already seen how to fetch API using the Resource feature. 👓 

Sometimes we need to fetch the API again under special circumstances such while network failure,  require to fetch content in a regular intervals etc.

Resource provide us way to re-fetch/ reuse the function. It really do return a re-fetch function and DOM will automatically render the changes after the re-fetch, since it a reactive signal.


const [posts, {refetch}] = createResource(() =>
....
);

How to call the re-fetch and where to call ? 😉

One of the ideal use is combine the call with a createEffetct.

In our example we have a search component and want to re fetch particular content based on the search text as the user type in.

createEffect((prev) => {

if (prev !== searchStore.searchString) {
console.log("Search Text changed");
refetch()
}
});

 That's all you need to know about refetch

 

 

Read More

Saturday, June 18, 2022

Fetch data from graphql API in Solidjs

 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

 

 

 

Read More