AA-410: Make sure alerts are cleaned up after being added (#324)
This commit is contained in:
@@ -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]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user