Creating a new query hook
In this guide, we will walk you through the process of creating a new query hook in Blueprint using React Query.
-
Create the hook file: Navigate to the appropriate directory within your app (e.g.,
apps/foundation/src/hooks) and create a new file for your hook (e.g.,useSampleQuery.ts). -
Write the hook code: Implement your hook using React Query and TypeScript. If the query is to a Kraken endpoint, use one of Blueprint's custom query hooks to ensure consistency in authentication and error handling (e.g.,
useKrakenQuery). Here is a basic example:import { useKrakenQuery } from '@foundation/infrastructure/api';
import { graphql } from '@foundation/gql-tada';
const sampleQuery = graphql(`
query Sample($id: String!) {
sample(id: $id) {
title
description
}
}
`);
interface UseSampleQueryArgs {
id: string;
}
export const useSampleQuery = ({ id }: UseSampleQueryArgs) =>
useKrakenQuery({
document: sampleQuery,
variables: { id },
queryKey: ['sampleData', id],
}); -
Use the hook: Import and use your new hook within your app as needed.
import { useSampleQuery } from '../hooks/useSampleQuery';
const SampleComponent = ({ id }: { id: string }) => {
const { data, error, isLoading } = useSampleQuery({ id });
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading data</div>;
return (
<div>
<h1>{data.sample.title}</h1>
<p>{data.sample.description}</p>
</div>
);
};
export default SampleComponent;