-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathuseDialogStore.tsx
67 lines (62 loc) · 1.67 KB
/
useDialogStore.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
57
58
59
60
61
62
63
64
65
66
67
// Code inspired by https://dev.to/dmtrkovalenko/the-neatest-way-to-handle-alert-dialogs-in-react-1aoe
// If you prefer to use Context API, refer to that link
import produce from 'immer';
import create from 'zustand';
import { AlertOptions } from '@/components/Alert';
type DialogStoreType = {
awaitingPromise: {
resolve?: () => void;
reject?: () => void;
};
open: boolean;
state: AlertOptions;
dialog: (options: Partial<AlertOptions>) => Promise<void>;
handleClose: () => void;
handleSubmit: () => void;
};
const useDialogStore = create<DialogStoreType>((set) => ({
awaitingPromise: {},
open: false,
state: {
title: 'Title',
description: 'Description',
submitText: 'Yes',
variant: 'warning',
catchOnCancel: false,
},
dialog: (options) => {
set(
produce((state: DialogStoreType) => {
state.open = true;
state.state = { ...state.state, ...options };
})
);
return new Promise<void>((resolve, reject) => {
set(
produce((state: DialogStoreType) => {
state.awaitingPromise = { resolve, reject };
})
);
});
},
handleClose: () => {
set(
produce((state: DialogStoreType) => {
// Allowing us to catch the promise
// Set catchOnCancel to false if you are not catching promise
// to avoid uncatched promise error.
state.state.catchOnCancel && state.awaitingPromise?.reject?.();
state.open = false;
})
);
},
handleSubmit: () => {
set(
produce((state: DialogStoreType) => {
state.awaitingPromise?.resolve?.();
state.open = false;
})
);
},
}));
export default useDialogStore;