Skip to content

Instantly share code, notes, and snippets.

@rohmanhm
Created November 12, 2023 02:47
Show Gist options
  • Save rohmanhm/c76778574a9c0bdc0bdb0055e92a125f to your computer and use it in GitHub Desktop.
Save rohmanhm/c76778574a9c0bdc0bdb0055e92a125f to your computer and use it in GitHub Desktop.

Filename

use{Service}{Action}.query.ts

Code

import { QueryObserverOptions, useQuery } from '@tanstack/react-query';

import { DataShape } from '@/types/api';

type Params = {
  id: number
  anything: any
};

/**
 * @example:
 * getServiceAction
 */
export const getServiceAction = async (
  params: Params
): Promise<string> => {
  const response = await fetch(`endpoint`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
  return response.json() as Promise<DataShape>;
};

/**
 * @example:
 * useServiceActionQuery
 */
const useServiceActionQuery = (
  params: Params,
  options: QueryObserverOptions<DataShape['data']>
) => {
  return useQuery(
    ['service-action', params.id],
    () => getServiceAction(params),
    {
      enabled: !!params.id,
      ...options,
    }
  );
};

export default useServiceActionQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment