| 31 | } |
| 32 | |
| 33 | export const useActions = (): UseActions => { |
| 34 | const client = useQueryClient(); |
| 35 | const { user } = useAuthContext(); |
| 36 | const { isSettled } = useShellState(); |
| 37 | const actionsKey = generateQueryKey(RequestKey.Actions, user); |
| 38 | |
| 39 | const { data, isPending } = useQuery({ |
| 40 | queryKey: actionsKey, |
| 41 | queryFn: async () => { |
| 42 | const serverData = await getUserActions(); |
| 43 | const current = client.getQueryData<ActionQueryData>(actionsKey); |
| 44 | |
| 45 | if (!current || !Array.isArray(current)) { |
| 46 | return { actions: serverData, serverLoaded: true }; |
| 47 | } |
| 48 | |
| 49 | const filtered = serverData.filter(({ type }) => |
| 50 | current.every((action) => action.type !== type), |
| 51 | ); |
| 52 | |
| 53 | return { actions: [...current, ...filtered], serverLoaded: true }; |
| 54 | }, |
| 55 | enabled: !!user && isSettled, |
| 56 | ...disabledRefetch, |
| 57 | }); |
| 58 | |
| 59 | const actions = useMemo(() => data?.actions ?? [], [data?.actions]); |
| 60 | const isActionsFetched = !isPending && !!data?.serverLoaded; |
| 61 | const queueRef = useRef<ActionType[]>([]); |
| 62 | |
| 63 | const { mutateAsync: completeAction } = useMutation({ |
| 64 | mutationFn: completeUserAction, |
| 65 | onMutate: (type) => { |
| 66 | if (!user?.id) { |
| 67 | queueRef.current = [...queueRef.current, type]; |
| 68 | return () => undefined; |
| 69 | } |
| 70 | |
| 71 | client.setQueryData<ActionQueryData>(actionsKey, (old) => { |
| 72 | const optimisticAction = { |
| 73 | userId: user.id, |
| 74 | type, |
| 75 | completedAt: new Date(), |
| 76 | }; |
| 77 | |
| 78 | if (!Array.isArray(old?.actions)) { |
| 79 | return { actions: [optimisticAction], serverLoaded: false }; |
| 80 | } |
| 81 | |
| 82 | // A forced resend runs on an action that is already in the cache. |
| 83 | if (old.actions.some((action) => action.type === type)) { |
| 84 | return old; |
| 85 | } |
| 86 | |
| 87 | return { |
| 88 | actions: [...old?.actions, optimisticAction], |
| 89 | serverLoaded: !!old?.serverLoaded, |
| 90 | }; |