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

usePosts.ts

25 lines621 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 const data = await response.json()
12 return data.filter((x: Post) => x.id <= limit)
14​
15const postsQueryOptions = (limit: number) =>
16 queryOptions({
17 queryKey: ['posts', limit],
18 queryFn: () => fetchPosts(limit),
19 })
20​
21const usePosts = (limit: number) => {
22 return useQuery(postsQueryOptions(limit))
24​
25export { usePosts, postsQueryOptions }