Last active
January 24, 2020 11:00
-
-
Save coryhouse/254595cf20a3b1ffbedce44aa7259f42 to your computer and use it in GitHub Desktop.
Hook for easily creating an alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Hook to make consuming Alert context more convenient | |
import { useContext } from "react"; | |
import AlertContext from "../components/AlertContext"; | |
import { ALERT_TYPES } from "reusable/lib/Alert"; | |
import { useHistory } from "react-router"; | |
export default function useAlert() { | |
const history = useHistory(); | |
const { setAlerts } = useContext(AlertContext); | |
/** Show an alert. Defaults to success. **NOTE**: This will NOT display an alert if | |
* you redirect immediately after calling this. | |
* Why? Because alerts are cleared when the URL changes. | |
* If you need to redirect, then show an alert, use `redirectAndAlert`. | |
* @param {Object} alert - Alert content. Accepts JSX. | |
* @param {string} [type=success] - Alert type. | |
* */ | |
function showAlert(alert, type = ALERT_TYPES.SUCCESS) { | |
setAlerts(alerts => [ | |
{ | |
type, | |
content: alert | |
}, | |
...alerts | |
]); | |
} | |
/** Redirect to a new page, then show an alert. Defaults to success alert. | |
* If you call the plain showAlert immediately before redirecting, the alert won't show | |
* because alerts are cleared when the URL changes. Alternatively, you can call | |
* showAlert **after** calling history.push so the alert is associated to the new URL. | |
* @param {string} path - Path to redirect to. | |
* @param {Object} alert - Alert content. Accepts JSX. | |
* @param {ALERT_TYPES} [ALERT_TYPES.SUCCESS] type - Alert type. | |
* */ | |
function redirectAndAlert(path, alert, type = ALERT_TYPES.SUCCESS) { | |
history.push(path); | |
setAlerts(alerts => [ | |
{ | |
type, | |
content: alert | |
}, | |
...alerts | |
]); | |
} | |
return { showAlert, redirectAndAlert }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment