Cannot DIsplay a Snackbar Notice on Button Click - Notice is undefined

I am trying to use withSelect and withDispatch to display an admin notice when save button is clicked. I am using the following code from this repo but it throws an error: notices is undefined. Here is the code I am using:

import { Icon, Button, SnackbarList } from '@wordpress/components';
import { dispatch, withSelect, withDispatch } from '@wordpress/data';
import { compose } from '@wordpress/compose';
// Display and Dispatch the notice
const NewNotices = ({ notices, removeNotice }) = {
    
    //Uncaught TypeError: notices is undefined
    const snackbarNotices = notices.filter((notice) = notice.type === 'snackbar');

    return (
        
            SnackbarList
                className=cwg-admin-notices
                notices={snackbarNotices}
                onRemove={removeNotice}
            /
        /
    );
}

export default compose([
    withSelect((select) = ({
        notices: select('core/notices').getNotices(),
    })),
    withDispatch((dispatch) = ({
        removeNotice: dispatch('core/notices').removeNotice,
    })),
])(NewNotices);

//Create the notice on btn click
Button
   isPrimary
   onClick={() =
   {
   settings.save();
   dispatch('core/notices')
   .createNotice(
   'success',
   __('Settings Saved', 'slug'),
   {
   type: 'snackbar',
   isDismissible: true,
   icon: 
   Icon icon=smiley /
   }
   );
   }}
   
   {__('Save', 'slug')}
/Button
NewNotices /
/

Topic notices rest-api Wordpress

Category Web


I figured it out. The component was not rerendering, when clicking the "Save" button. I included the compose component in the render method and all is working good now:

const Notices = ({ notices, removeNotice }) => {

    const snackbarNotices = notices ? notices.filter((notice) => notice.type === 'snackbar') : [];
    return (
        <>
            <SnackbarList
                className="cwg-admin-notices"
                notices={snackbarNotices}
                onRemove={removeNotice}
            />
        </>
    );
}

const AppNotices = compose(
    withSelect((select) => ({
        notices: select('core/notices').getNotices(),
    })),
    withDispatch((dispatch) => ({
        removeNotice: dispatch('core/notices').removeNotice,
    })),
)(Notices);

--

<Button
   isPrimary
   onClick={() =>
       {
       settings.save();
       dispatch('core/notices')
       .createNotice(
           'success',
           __('Settings Saved', 'slug'),
           {
           type: 'snackbar',
           isDismissible: true,
           icon: <Icon icon="smiley" />
           }
       );
   }}
   >
   {__('Save', 'slug')}
</Button>
<AppNotices/>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.