()
| 20 | } |
| 21 | |
| 22 | export const useActions = (): UseActions => { |
| 23 | const client = useQueryClient(); |
| 24 | const { user } = useAuthContext(); |
| 25 | const { isSettled } = useShellState(); |
| 26 | const actionsKey = generateQueryKey(RequestKey.Actions, user); |
| 27 | |
| 28 | const { data, isPending } = useQuery({ |
| 29 | queryKey: actionsKey, |
| 30 | queryFn: async () => { |
| 31 | const serverData = await getUserActions(); |
| 32 | const current = client.getQueryData<ActionQueryData>(actionsKey); |
| 33 | |
| 34 | if (!current || !Array.isArray(current)) { |
| 35 | return { actions: serverData, serverLoaded: true }; |
| 36 | } |
| 37 | |
| 38 | const filtered = serverData.filter(({ type }) => |
| 39 | current.every((action) => action.type !== type), |
| 40 | ); |
| 41 | |
| 42 | return { actions: [...current, ...filtered], serverLoaded: true }; |
| 43 | }, |
| 44 | enabled: !!user && isSettled, |
| 45 | ...disabledRefetch, |
| 46 | }); |
| 47 | |
| 48 | const actions = useMemo(() => data?.actions ?? [], [data?.actions]); |
| 49 | const isActionsFetched = !isPending && !!data?.serverLoaded; |
| 50 | const queueRef = useRef<ActionType[]>([]); |
| 51 | |
| 52 | const { mutateAsync: completeAction } = useMutation({ |
| 53 | mutationFn: completeUserAction, |
| 54 | onMutate: (type) => { |
| 55 | if (!user?.id) { |
| 56 | queueRef.current = [...queueRef.current, type]; |
| 57 | return () => undefined; |
| 58 | } |
| 59 | |
| 60 | client.setQueryData<ActionQueryData>(actionsKey, (old) => { |
| 61 | const optimisticAction = { |
| 62 | userId: user.id, |
| 63 | type, |
| 64 | completedAt: new Date(), |
| 65 | }; |
| 66 | |
| 67 | if (!Array.isArray(old?.actions)) { |
| 68 | return { actions: [optimisticAction], serverLoaded: false }; |
| 69 | } |
| 70 | |
| 71 | return { |
| 72 | actions: [...old?.actions, optimisticAction], |
| 73 | serverLoaded: !!old?.serverLoaded, |
| 74 | }; |
| 75 | }); |
| 76 | |
| 77 | return () => |
| 78 | client.setQueryData<ActionQueryData>(actionsKey, { |
| 79 | actions, |
no test coverage detected