({
id,
options = {},
}: UsePostByIdProps)
| 92 | }; |
| 93 | |
| 94 | export const usePostById = ({ |
| 95 | id, |
| 96 | options = {}, |
| 97 | }: UsePostByIdProps): UsePostById => { |
| 98 | const { initialData, ...restOptions } = options; |
| 99 | const { tokenRefreshed } = useAuthContext(); |
| 100 | const key = getPostByIdKey(id); |
| 101 | const { fetchTranslations } = useTranslation({ |
| 102 | queryKey: key, |
| 103 | queryType: 'post', |
| 104 | }); |
| 105 | const { |
| 106 | data: postById, |
| 107 | isError, |
| 108 | isPending, |
| 109 | } = useQuery<PostData>({ |
| 110 | queryKey: key, |
| 111 | queryFn: async () => { |
| 112 | const res = await gqlClient.request<PostData>(POST_BY_ID_QUERY, { id }); |
| 113 | fetchTranslations([res.post]); |
| 114 | |
| 115 | return res; |
| 116 | }, |
| 117 | ...restOptions, |
| 118 | staleTime: StaleTime.Default, |
| 119 | enabled: !!id && tokenRefreshed, |
| 120 | }); |
| 121 | const post = postById || (options?.initialData as PostData); |
| 122 | |
| 123 | useMutationSubscription({ |
| 124 | matcher: contentPreferenceMutationMatcher, |
| 125 | callback: ({ mutation, variables: mutationVariables, queryClient }) => { |
| 126 | const currentData = queryClient.getQueryData(key); |
| 127 | const [requestKey] = mutation.options.mutationKey as [ |
| 128 | RequestKey, |
| 129 | ...unknown[], |
| 130 | ]; |
| 131 | |
| 132 | if (!currentData) { |
| 133 | return; |
| 134 | } |
| 135 | |
| 136 | const nextStatus = mutationKeyToContentPreferenceStatusMap[requestKey]; |
| 137 | |
| 138 | const { id: entityId, entity } = |
| 139 | mutationVariables as PropsParameters<ContentPreferenceMutation>; |
| 140 | |
| 141 | queryClient.setQueryData<PostData>(key, (data) => { |
| 142 | const newPostData = updatePostContentPreference({ |
| 143 | data: data.post, |
| 144 | status: nextStatus, |
| 145 | entityId, |
| 146 | entity, |
| 147 | }); |
| 148 | |
| 149 | return { |
| 150 | ...data, |
| 151 | post: newPostData, |
no test coverage detected