1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-24 20:36:40 +07:00

notifications: updating lastSeen when list is opened

This commit is contained in:
Fedor Katurov 2023-03-11 19:30:18 +06:00
parent a39d000ff2
commit 97590d88af
7 changed files with 88 additions and 4 deletions

View file

@ -1,25 +1,68 @@
import { useCallback, useState } from 'react';
import { isValid, parseISO } from 'date-fns';
import useSWR from 'swr';
import { apiGetNotificationSettings } from '~/api/notifications/settings';
import {
apiGetNotificationSettings,
apiUpdateNotificationSettings,
} from '~/api/notifications/settings';
import { ApiUpdateNotificationSettingsRequest } from '~/api/notifications/types';
import { API } from '~/constants/api';
import { getErrorMessage } from '~/utils/errors/getErrorMessage';
import { showErrorToast } from '~/utils/errors/showToast';
import { useAuth } from '../auth/useAuth';
const refreshInterval = 60e3; // 1min
export const useNotificationSettingsRequest = () => {
const [isUpdating, setIsUpdating] = useState(false);
const [updateError, setUpdateError] = useState('');
const { isUser } = useAuth();
const {
data,
isValidating: isLoading,
error,
mutate,
} = useSWR(
isUser ? API.NOTIFICATIONS.SETTINGS : null,
async () => apiGetNotificationSettings(),
{ refreshInterval },
);
const update = useCallback(
async (settings: ApiUpdateNotificationSettingsRequest) => {
if (!data) {
return;
}
try {
setIsUpdating(true);
setUpdateError('');
mutate({ ...data, ...settings }, { revalidate: false });
const result = await apiUpdateNotificationSettings(settings);
mutate(result, { revalidate: false });
} catch (error) {
mutate(data, { revalidate: false });
const message = getErrorMessage(error);
if (message) {
setUpdateError(message);
}
showErrorToast(error);
} finally {
setIsUpdating(true);
}
},
[data, mutate],
);
return {
isLoading,
error,
@ -32,5 +75,8 @@ export const useNotificationSettingsRequest = () => {
? parseISO(data?.last_date)
: undefined,
enabled: !!data?.enabled && (data.flow || data.comments),
update,
updateError,
isUpdating,
};
};