Update selected item color in Pass menu
[ProtonMail-WebClient.git] / packages / pass / hooks / useAliasOptions.ts
blobfd2e3f473d677a5f5e1351bdd49a1ad23fc6e583
1 import { useEffect, useMemo } from 'react';
2 import { useSelector } from 'react-redux';
4 import { getAliasOptionsIntent } from '@proton/pass/store/actions';
5 import { aliasOptionsRequest } from '@proton/pass/store/actions/requests';
6 import { selectAliasOptions } from '@proton/pass/store/selectors';
7 import type { MaybeNull, MaybePromise } from '@proton/pass/types';
8 import type { AliasMailbox } from '@proton/pass/types/data/alias';
9 import noop from '@proton/utils/noop';
11 import { useActionRequest } from './useActionRequest';
13 export type SanitizedAliasOptions = {
14     suffixes: { value: string; signature: string }[];
15     mailboxes: AliasMailbox[];
18 export type UseAliasOptionsParams = {
19     lazy?: boolean /* defer the alias options dispatch */;
20     shareId: string;
21     onAliasOptionsLoaded?: (aliasOptions: SanitizedAliasOptions) => MaybePromise<void>;
24 export type UseAliasOptionsResult = {
25     loading: boolean;
26     request: () => void;
27     value: MaybeNull<SanitizedAliasOptions>;
30 export const useAliasOptions = ({
31     shareId,
32     lazy = false,
33     onAliasOptionsLoaded,
34 }: UseAliasOptionsParams): UseAliasOptionsResult => {
35     const aliasOptions = useSelector(selectAliasOptions);
37     const sanitizedAliasOptions = useMemo(
38         () =>
39             aliasOptions !== null
40                 ? {
41                       suffixes: aliasOptions.suffixes.map(({ suffix, signedSuffix }) => ({
42                           value: suffix,
43                           signature: signedSuffix,
44                       })),
45                       mailboxes: aliasOptions.mailboxes,
46                   }
47                 : null,
48         [aliasOptions]
49     );
51     const getAliasOptions = useActionRequest(getAliasOptionsIntent, {
52         initialRequestId: aliasOptionsRequest(shareId),
53         onSuccess: sanitizedAliasOptions ? () => onAliasOptionsLoaded?.(sanitizedAliasOptions) : noop,
54     });
56     useEffect(() => {
57         if (!lazy) getAliasOptions.dispatch({ shareId });
58     }, [lazy]);
60     return useMemo(
61         () => ({
62             loading: getAliasOptions.loading,
63             request: () => getAliasOptions.dispatch({ shareId }),
64             value: sanitizedAliasOptions,
65         }),
66         [sanitizedAliasOptions, getAliasOptions.loading, shareId]
67     );