2

I have a use case where max number of toast that can be displayed at a time is 2. If there are more than 2 toast then the total Number of toast is also displayed within the currently displayed 2 toasts.

User Action 1 - The user can click on the total number to expand and view all toasts there is. Up to this part I've everything working for me.

User Action 2 - If the user clicks on the total number of toast again then hide the rest of the toast and go back to only display 2 toast at a time. This is what is not working for me. Once I can achieve this then ofcourse I would also like to show back again all toast there is as mentioned in User Action 1.

On the NotificationManager component, I set default maxToast as 2. Then onClick handleMaxNotification() will change the the max toast value to null - which displays all toast there is (this is working).

handleMaxNotification() will also toggle back the maxToast to 2 and on the local state it does set the values correctly, however react-toastify doesn't reflect that in the UI. for e.g. displayed 4 toast doesn't go back 2. Help is much appreciated!

export default function NotificationManager() {
    const [maxToast, setMaxToast] = useState(2); // default
    const [displayAllNotification, setDisplayAllNotification] = useState(false);

    const handleMaxNotification = () => {
        setDisplayAllNotification(v => !v);
    };

    useEffect(() => {
        if (displayAllNotification)
            setMaxToast(null);
        else
            setMaxToast(2);
    }, [displayAllNotification]);

    return (<>
        <ToastContainer
            newestOnTop={true}
            limit={maxToast}
        />
        <Notification
            maxToast={maxToast}
            handleMaxNotification={handleMaxNotification}
            displayAllNotification={displayAllNotification}
        />
    </>);
}

This is the component that display toast.

import { displayToast } from '../components/toast/displayToast';

const Notification = ({handleMaxNotification, maxToast, displayAllNotification}) => {

    const notifications = useSelector(state => state.notifications);
    const totalNotification = notifications.length > 2 ? notifications.length : ''; 
 
    const Toast = () => (
        <div>
            <span onClick={() => handleMaxNotification()}>{totalNotification}</span>
            <span><Icon name='circle' /></span><span>Notification</span>
        </div>
    );

    const showNotification = (id) => {
        const toastOptions = { toastId: id };
        displayToast(Toast, toastOptions);
    };

    const handleNotification = () => {
        notifications.forEach(({ id }) => showNotification(id));
    };

    useEffect(() => {
        handleNotification();
    }, [notifications, maxToast, displayAllNotification]);

    return (<span></span>);
};


export default Notification;
Jereme
  • 427
  • 7
  • 15

0 Answers0