Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Last active May 7, 2024 21:17
Show Gist options
  • Save aneurysmjs/458da04db371dc23f1268f0a1473e709 to your computer and use it in GitHub Desktop.
Save aneurysmjs/458da04db371dc23f1268f0a1473e709 to your computer and use it in GitHub Desktop.
react query hook
describe('useQueryProductById', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should return a single product', async () => {
const product = {
id: 2,
title: 'Mens Casual Premium Slim Fit T-Shirts ',
price: 22.3,
description: 'lorem ipsum',
category: "men's clothing",
image: 'https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg',
rating: {
rate: 4.1,
count: 259,
},
};
mockAxios.get.mockResolvedValue({ data: product });
const { result } = renderHook(() => useQueryProductById('1'), { wrapper });
await waitFor(() => expect(result.current.data).toStrictEqual(product));
});
});
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import type { Product } from '@/modules/products/types';
export default function useQueryProductById(productId: string) {
return useQuery({
queryKey: ['products', productId],
queryFn: async () => {
try {
const response = await axios.get<Product>(`https://fakestoreapi.com/products/${productId}`);
return response.data;
} catch (error) {
throw new Error('Error while fetching products');
}
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment