Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

usePosts.ts

26 lines682 Bytes

1import { queryOptions, useQuery } from '@tanstack/react-query'
2​
3type Post = {
4 id: number
5 title: string
6 body: string
7}
8​
9const fetchPosts = async (limit: number): Promise<Array<Post>> => {
10 const response = await fetch('https://jsonplaceholder.typicode.com/posts')
11 if (!response.ok) throw new Error('Failed to fetch posts')
12 const data = await response.json()
13 return data.filter((x: Post) => x.id <= limit)
15​
16const postsQueryOptions = (limit: number) =>
17 queryOptions({
18 queryKey: ['posts', limit],
19 queryFn: () => fetchPosts(limit),
20 })
21​
22const usePosts = (limit: number) => {
23 return useQuery(postsQueryOptions(limit))
25​
26export { usePosts, postsQueryOptions }