Just got started with Zustand. Trying to implement a confirm dialog. It is working but i can't get the last bit. I am trying to get a return value if the user declined the dialog, however i am lacking the understanding.
This is what i got so far. Calling the confirm Dialog:
confirmDialog("Are you sure?", (userAccepted) => {
replace(userAccepted)
})
// I am not able to run code if a user declines the dialog. confirmDialog yields void
function replace(userAccepted: boolean) {
...
}
I am struggeling with running code when a user declines the dialog.
This is my store:
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, Box, IconButton, Alert } from "@pankod/refine-mui"
import create from "zustand"
type ConfirmDialogStore = {
message: string
onSubmit?: (userAccepted: boolean) => void
close: () => void
}
const useConfirmDialogStore = create<ConfirmDialogStore>((set) => ({
//states and their default values
message: "",
onSubmit: undefined,
// Updating state via close property (which is a function)
close: () => set({ onSubmit: undefined }),
}))
export const confirmDialog = (message: string, onSubmit: (userAccepted: boolean) => void) => {
// Schreibt in den Store
useConfirmDialogStore.setState({
message,
onSubmit,
})
}
const ConfirmDialog = () => {
// Liest aus dem Store
const { message, onSubmit, close } = useConfirmDialogStore()
// This will be rendered if Boolean(onSubmit) is true / if onSubmit is provided
return (
<Dialog
open={Boolean(onSubmit)}
onClose={close}
maxWidth="sm"
fullWidth
>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
>
<DialogTitle>Bist du Sicher?</DialogTitle>
<IconButton onClick={close}>{/* <Close /> */}</IconButton>
</Box>
<DialogContent>
<Alert severity="error">{message}</Alert>
</DialogContent>
<DialogActions sx={{ padding: (theme) => theme.spacing(2) }}>
<Button
color="primary"
variant="contained"
onClick={close}
>
Cancel
</Button>
<Button
color="secondary"
variant="contained"
onClick={() => {
if (onSubmit) {
onSubmit(true)
}
close()
}}
>
Confirm
</Button>
</DialogActions>
</Dialog>
)
}
export default ConfirmDialog