-
Notifications
You must be signed in to change notification settings - Fork 67
/
Settings.provider.tsx
56 lines (43 loc) 路 1.71 KB
/
Settings.provider.tsx
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
import {noop} from 'lodash';
import {createContext, useCallback, useContext, useMemo} from 'react';
import TracetestAPI from 'redux/apis/Tracetest';
import {TDraftResource} from 'types/Settings.types';
import {useNotification} from '../Notification/Notification.provider';
interface IContext {
isLoading: boolean;
onSubmit(resource: TDraftResource[]): void;
}
const Context = createContext<IContext>({isLoading: false, onSubmit: noop});
interface IProps {
children: React.ReactNode;
}
export const useSettings = () => useContext(Context);
const SettingsProvider = ({children}: IProps) => {
const {useCreateSettingMutation, useUpdateSettingMutation} = TracetestAPI.instance;
const {showNotification} = useNotification();
const [createSetting, {isLoading: isLoadingCreate}] = useCreateSettingMutation();
const [updateSetting, {isLoading: isLoadingUpdate}] = useUpdateSettingMutation();
const onSaveResource = useCallback(
async (resource: TDraftResource) => {
if (resource.spec.id) {
await updateSetting({resource});
} else {
await createSetting({resource});
}
},
[createSetting, updateSetting]
);
const onSubmit = useCallback(
async (resources: TDraftResource[]) => {
await Promise.all(resources.map(resource => onSaveResource(resource)));
showNotification({type: 'success', title: 'Settings saved', description: 'Your settings were saved'});
},
[onSaveResource, showNotification]
);
const value = useMemo<IContext>(
() => ({isLoading: isLoadingCreate || isLoadingUpdate, onSubmit}),
[isLoadingCreate, isLoadingUpdate, onSubmit]
);
return <Context.Provider value={value}>{children}</Context.Provider>;
};
export default SettingsProvider;