Fetching Data with React Query and TypeScript II

vikirobles

Vicky Vasilopoulou

Posted on March 1, 2022

Fetching Data with React Query and TypeScript II

Below you can see a way of fetching data using React query and TypeScript.

  • React Query Link

  • 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)
Enter fullscreen mode Exit fullscreen mode
  1. 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);
    }
  });
};
Enter fullscreen mode Exit fullscreen mode
  1. Lets say we have a list of doctors that we want to fetch.
  2. 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;
}
Enter fullscreen mode Exit fullscreen mode
  1. 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,
  };
};
Enter fullscreen mode Exit fullscreen mode
  1. Then on the component you want to use this data you can bring it simply as:
const { doctorsData } = useFetchDoctors();
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
vikirobles
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.

Related