Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active January 24, 2020 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhouse/254595cf20a3b1ffbedce44aa7259f42 to your computer and use it in GitHub Desktop.
Save coryhouse/254595cf20a3b1ffbedce44aa7259f42 to your computer and use it in GitHub Desktop.
Hook for easily creating an alert
// 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