AA-410: Make sure alerts are cleaned up after being added (#324)

This commit is contained in:
Michael Terry
2021-01-25 12:41:32 -05:00
committed by GitHub
parent 47fd6bfe18
commit 9ef3787d4b
7 changed files with 30 additions and 27 deletions

View File

@@ -1,12 +1,11 @@
/* eslint-disable import/prefer-default-export */
import { useContext, useState, useEffect } from 'react';
import { useContext, useEffect } from 'react';
import UserMessagesContext from './UserMessagesContext';
export function useAlert(isVisible, {
code, text, topic, type, payload, dismissible,
}) {
const { add, remove } = useContext(UserMessagesContext);
const [alertId, setAlertId] = useState(null);
// Please note:
// The deps list [isVisible, code, ... etc.] in this `useEffect` call prevents the
@@ -18,20 +17,19 @@ export function useAlert(isVisible, {
// We hope to address the underlying issue in TNL-7418.
// In the mean time, you may follow the pattern that `useAccessExpirationAlert`
// establishes: memoize the payload so that the exact same object is used if the
// payload has not changed.
// payload has not changed. And don't put values based off of now() in your payload, as
// that breaks memoization.
useEffect(() => {
if (isVisible && alertId === null) {
setAlertId(add({
code, text, topic, type, payload, dismissible,
}));
} else if (!isVisible && alertId !== null) {
remove(alertId);
setAlertId(null);
if (!isVisible) {
return undefined;
}
const cleanupId = add({
code, text, topic, type, payload, dismissible,
});
return () => {
if (alertId !== null) {
remove(alertId);
}
remove(cleanupId);
};
}, [isVisible, code, text, topic, type, dismissible, payload]);
}, [isVisible, code, text, topic, type, payload, dismissible]);
}