Fetching Data with React Query and TypeScript II
Vicky Vasilopoulou
Posted on March 1, 2022
Below you can see a way of fetching data using React query and TypeScript.
You can use Transform tool that transforms JSON files to TypeScript and much more. This tool is quite handy when you have nested data.
You need to create your graphql Client.
In my case I used the graphql-request:
import { GraphQLClient } from 'graphql-request'
const endpoint = `ADD YOUR ENDPOINT HERE`
export const graphQlClient = new GraphQLClient(endpoint)
- Then you can make your
useGqlQuery.ts
file.
import { QueryKey, useQuery, UseQueryResult } from 'react-query';
import { graphQlClient } from '../../graphql/client';
export const useGqlQuery = <ResponseData = unknown, Variables = unknown>(
queryKey: QueryKey,
query: string,
variables?: Variables,
): UseQueryResult<ResponseData, Error> => {
return useQuery(queryKey, async () => {
try {
const response = await graphQlClient.request(query, variables);
return response;
} catch (error) {
console.log(error);
}
});
};
- Lets say we have a list of doctors that we want to fetch.
- First we need to create the types of the data that we get as a model.
export interface DoctorsDataModel {
doctors: Doctor[];
}
export interface Doctor {
first_name: string;
last_name: string;
doctor_id: string;
}
- We can create our custom hook that will fetch our data.
export const useFetchDoctors = () => {
const getDoctorsData = useGqlQuery<DoctorsDataModel>('getDoctorsData', GET_ALL_DOCTORS);
const doctorsData = useMemo(() => getDoctorsData?.data?.doctors, [getDoctorsData]);
return {
doctorsData,
};
};
- Then on the component you want to use this data you can bring it simply as:
const { doctorsData } = useFetchDoctors();
For mutations the schema is a little bit different:
export const useMutation = <Response = unknown, Variables = unknown>(
query: string,
sideEffects?: UseMutationOptions<Response, Error, Variables, unknown>,
): UseMutationResult<Response, Error, Variables, unknown> => {
return useMutation(async (variables) => {
const yourToken = 'YOURTOKEN'
return graphQlClient.request(query, variables, {
Authorization: XXXXX,
})
}, sideEffects)
}
💖 💪 🙅 🚩
Vicky Vasilopoulou
Posted on March 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.