posts.ts63 lines, 1.9 KB
| 1 | import { |
| 2 | infiniteQueryOptions, |
| 3 | useMutation, |
| 4 | type InfiniteData, |
| 5 | type QueryClient, |
| 6 | } from '@tanstack/react-query' |
| 7 | import { request, type Page, type Post } from '../../lib/api' |
| 8 | import { toast } from '../../lib/toast' |
| 9 | |
| 10 | // A list of posts, a page at a time: the home feed is ['posts', 'home'], |
| 11 | // a profile ['posts', '@user1']. The cursor is the last post's id. |
| 12 | export const postsOptions = (path: string, name: string) => |
| 13 | infiniteQueryOptions({ |
| 14 | queryKey: ['posts', name], |
| 15 | queryFn: ({ pageParam }) => |
| 16 | request<Page>(`${path}?cursor=${pageParam || ''}`), |
| 17 | initialPageParam: 0, |
| 18 | getNextPageParam: (last) => last.next_cursor, |
| 19 | }) |
| 20 | |
| 21 | // updatePost changes one post in every list that holds it. |
| 22 | export function updatePost( |
| 23 | client: QueryClient, |
| 24 | id: number, |
| 25 | change: (post: Post) => Post, |
| 26 | ) { |
| 27 | client.setQueriesData<InfiniteData<Page>>( |
| 28 | { queryKey: ['posts'] }, |
| 29 | (data) => |
| 30 | data && { |
| 31 | ...data, |
| 32 | pages: data.pages.map((page) => ({ |
| 33 | ...page, |
| 34 | posts: page.posts.map((p) => (p.id === id ? change(p) : p)), |
| 35 | })), |
| 36 | }, |
| 37 | ) |
| 38 | } |
| 39 | |
| 40 | // useLike likes or unlikes at once, and asks the server afterwards. |
| 41 | // There's no refetch when it answers: the worker adds likes up once a |
| 42 | // second, and a replica may be older still, so a refetch would bring |
| 43 | // back the old count for a moment. |
| 44 | export function useLike() { |
| 45 | return useMutation({ |
| 46 | mutationFn: (post: Post) => |
| 47 | request(`/posts/${post.id}/like`, { |
| 48 | method: post.liked ? 'DELETE' : 'POST', |
| 49 | }), |
| 50 | onMutate: async (post, { client }) => { |
| 51 | await client.cancelQueries({ queryKey: ['posts'] }) |
| 52 | updatePost(client, post.id, (p) => ({ |
| 53 | ...p, |
| 54 | liked: !post.liked, |
| 55 | likes: p.likes + (post.liked ? -1 : 1), |
| 56 | })) |
| 57 | }, |
| 58 | onError: (_error, post, _result, { client }) => { |
| 59 | updatePost(client, post.id, () => post) |
| 60 | toast("That like didn't go through.") |
| 61 | }, |
| 62 | }) |
| 63 | } |