({ post }: { post?: Post })
| 21 | }; |
| 22 | |
| 23 | export const usePostActions = ({ post }: { post?: Post }): UsePostActions => { |
| 24 | const client = useQueryClient(); |
| 25 | const postId = post?.id; |
| 26 | const key = useMemo(() => { |
| 27 | if (!postId) { |
| 28 | return [RequestKey.PostActions, 'missing-post']; |
| 29 | } |
| 30 | |
| 31 | return generateQueryKey(RequestKey.PostActions, { id: postId }); |
| 32 | }, [postId]); |
| 33 | |
| 34 | const queryFn = useCallback((): PostActionData => { |
| 35 | return defaultPostActionData; |
| 36 | }, []); |
| 37 | |
| 38 | const { data } = useQuery({ |
| 39 | queryKey: key, |
| 40 | queryFn, |
| 41 | initialData: queryFn, |
| 42 | staleTime: Infinity, |
| 43 | gcTime: Infinity, |
| 44 | enabled: !!postId, |
| 45 | ...disabledRefetch, |
| 46 | }); |
| 47 | const actionData = data ?? queryFn(); |
| 48 | |
| 49 | const onInteract = useCallback( |
| 50 | (interaction: PostActionData['interaction']) => { |
| 51 | if (!postId) { |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | client.setQueryData<PostActionData>(key, { |
| 56 | interaction, |
| 57 | previousInteraction: |
| 58 | actionData.interaction === interaction |
| 59 | ? 'none' |
| 60 | : actionData.interaction, |
| 61 | }); |
| 62 | }, |
| 63 | [client, key, actionData.interaction, postId], |
| 64 | ); |
| 65 | |
| 66 | return { |
| 67 | interaction: actionData.interaction, |
| 68 | previousInteraction: actionData.previousInteraction, |
| 69 | onInteract, |
| 70 | }; |
| 71 | }; |
no test coverage detected