React Query

React Query

You can integrate Aetheris into your React application using React Query (opens in a new tab). React Query is a powerful library that provides hooks for fetching, caching, and updating data in your application. To use it, you will need to install the @tanstack/react-query package, as well as the @aetheris/react-query package.

Installation

This guide assumes you have already setup @aetheris/client on your frontend. If you haven't, you can reference the documentation on the client and quick start guide pages.

pnpm add @tanstack/react-query @aetheris/react-query 

Setup

The rest of this guide will walk you through the process of setting up React Query with Aetheris.

Create the client

Start by creating a file for your client. This file will contain the api client and the React Query client.

src/lib/api.ts
import type { App } from "@/server";
import { createClient, httpLink } from "@aetheris/client";
 
export const api = createClient<App>({
    links:[
        httpLink({
            baseUrl: "http://localhost:3000/api",
        }),
    ],
});

This is the same client we created in the vanilla guide. To make this work with React Query, we need to create the client using createAetherisReact

src/lib/api.ts
import type { App } from "@/server";
import { createClient, httpLink } from "@aetheris/client";
import { createAetherisReact } from "@aetheris/react-query";
 
export const api = createClient<App>({
    links:[
        httpLink({
            baseUrl: "http://localhost:3000/api",
        }),
    ],
});
 
export const { AetherisProvider, client, useAetherisContext } = createAetherisReact(api);

The createAetherisReact function takes the api client and returns a provider, client, and context hook for using the query client in your application.

Setup the providers

Now we will need to setup the provider for your query client. This is done by wrapping your application in the AetherisProvider component.

src/App.tsx
import { QueryClient} from "@tanstack/react-query";
import { AetherisProvider } from "@/lib/api";
 
const queryClient = new QueryClient();
 
const App = () => {
    return (
        <AetherisProvider queryClient={queryClient}>
            {/* Your application */}
        </AetherisProvider>
    );
};

Using the client

Now the client is setup, you can use the client object to call your API routes. The client will automatically infer any inputs or outputs from the api endpoints you created.

src/components/post.tsx
import { client } from "@/lib/api";
 
const Post = () => {
    const { data, error } = await client.getPost.useQuery({
        input: { id: 1 },
    });
 
    if (error) {
        return <div>Error: {error.message}</div>;
    }
 
    if (!data) {
        return <div>Loading...</div>;
    }
 
    return <div>{post.title}</div>;
};