I have a custom hook for notification widgetsuseNotifications
. This hook returns an array containing the next element (it is similar to the ant.design message api):
add
: Function to add new notificationremove
: Function to get the notification ID and delete the notificationcontextHandler
: JSXWhen the user calls add
, they are given an ID that can be used to delete the notification
This question is specifically about the delete function. Since I'm calling this function right after adding a new notification, the function receives a copy of the old list, so no new elements, and an error is thrown. How can I fix it so that the components use the same API?
useNotification hook How do I use it
Codesandbox (for testing, I did setTimeout
and it called remove()
within 3 seconds): https://codesandbox.io/s/goofy-smoke -5q7dw3?file=/src/App.js:405-440
You can make your
remove
function use the status updater function, which has access to the latest status value. This allows you to access the newlist
state before the component is re-rendered inremove()
.Note: You are currently altering the original state by setting the nested object's
isMounted
property tofalse
. Even if you copy the array, you should also copy the object being updated to avoid re-rendering issues.Here are some modifications on how to access the latest value of the state and avoid state mutations:
See examples below: