-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathindex.ts
More file actions
95 lines (82 loc) · 2.71 KB
/
index.ts
File metadata and controls
95 lines (82 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { use, useCallback, useState } from 'react';
import useUASFetchSaveStatus from '#app/hooks/useUASFetchSaveStatus';
import { AccountContext } from '#app/contexts/AccountContext';
import isLocal from '#app/lib/utilities/isLocal';
import uasApiRequest from '#app/lib/uasApi';
import {
FAVOURITES_CONFIG,
createFavouritesPayload,
} from '#app/lib/uasApi/uasUtility';
import useToggle from '../useToggle';
/** A hook that fetches an article’s saved status and controls showing the save UAS button
* based on feature toggles and sign in status,
* with room to later expand for toggling the save state based on user actions. */
interface UseUASButtonProps {
articleId: string;
service: string;
title: string;
}
type UASAction = 'save' | 'remove';
interface UseUASButtonReturn {
showButton: boolean;
isSaved: boolean;
isLoading: boolean;
error: Error | null;
handleSaveAction: (action: UASAction) => Promise<void>;
}
const useUASButton = ({
service,
articleId,
title,
}: UseUASButtonProps): UseUASButtonReturn => {
const { isSignedIn } = use(AccountContext);
const { enabled: featureToggleOn = false, value: accountService = '' } =
useToggle('uasPersonalization');
const [isSaving, setIsSaving] = useState(false);
const [saveError, setSaveError] = useState<Error | null>(null);
const isUASEnabled =
featureToggleOn &&
(isLocal()
? accountService?.toString().split('|').includes(service)
: true);
const showButton = isUASEnabled && isSignedIn;
const { isSaved, isLoading, error, setIsSaved } = useUASFetchSaveStatus(
showButton ? articleId : '',
);
const handleSaveAction = useCallback(
async (action: UASAction) => {
if (isSaving) return;
setIsSaving(true);
try {
setSaveError(null);
if (action === 'save') {
const body = createFavouritesPayload({ articleId, service, title });
await uasApiRequest('POST', FAVOURITES_CONFIG.activityType, { body });
setIsSaved(true);
} else {
// TO be implemented with https://bbc.atlassian.net/browse/WS-2212
// const globalId = buildGlobalId(articleId);
// await uasApiRequest('DELETE', FAVOURITES_CONFIG.activityType, {
// globalId,
// });
setIsSaved(false);
}
} catch (err) {
const saveErr = err instanceof Error ? err : new Error(String(err));
setSaveError(saveErr);
throw saveErr;
} finally {
setIsSaving(false);
}
},
[articleId, service, title, isSaving, setIsSaved],
);
return {
showButton,
isSaved,
isLoading: isLoading || isSaving,
error: saveError || error,
handleSaveAction,
};
};
export default useUASButton;