| 1 | import { useMutation } from '@tanstack/react-query' |
| 2 | import { request } from '../../lib/api' |
| 3 | |
| 4 | type Props = { handle: string; following: boolean } |
| 5 | |
| 6 | // The button shows what you asked for while the server works on it, |
| 7 | // and the refetches after it bring the counts. |
| 8 | export function FollowButton({ handle, following }: Props) { |
| 9 | const follow = useMutation({ |
| 10 | mutationFn: (on: boolean) => |
| 11 | request(`/users/${handle}/follow`, { |
| 12 | method: on ? 'POST' : 'DELETE', |
| 13 | }), |
| 14 | onSettled: (_data, _error, _on, _result, { client }) => |
| 15 | Promise.all([ |
| 16 | client.invalidateQueries({ queryKey: ['user', handle] }), |
| 17 | client.invalidateQueries({ queryKey: ['suggestions'] }), |
| 18 | client.invalidateQueries({ queryKey: ['posts', 'home'] }), |
| 19 | ]), |
| 20 | }) |
| 21 | const on = follow.isPending ? follow.variables : following |
| 22 | return ( |
| 23 | <button |
| 24 | onClick={() => follow.mutate(!on)} |
| 25 | className={on ? 'btn-quiet text-mute' : 'btn-quiet border-mute'} |
| 26 | > |
| 27 | {on ? 'Following' : 'Follow'} |
| 28 | </button> |
| 29 | ) |
| 30 | } |