Unable to show a snackbar in WordPress Editor

59 Views Asked by At

I am a newbie in JS, stuck in an issue here. No matter what I try, I am unable to throw a snackbar when any error is caught. I am also not sure how I import dispatch and use that. Any assistance is really appreciated. I managed to show an Editor notice, but I need to show a snackbar instead. For your reference, this is the onAddTerm const of the /wp-includes/js/dist/editor.js

const { createErrorNotice } = wp.data.dispatch('core/notices'); // Importing dispatch function

  const onAddTerm = async (event) => {
    try {
      var _taxonomy$labels$sing;
    
      event.preventDefault();
    
      if (formName === '' || adding) {
        return;
      }
    
      const existingTerm = findTerm(availableTerms, formParent, formName);
    
      if (existingTerm) {
        // If the term we are adding exists but is not selected select it.
        if (!terms.some((term) => term === existingTerm.id)) {
          onUpdateTerms([...terms, existingTerm.id]);
        }
    
        setFormName('');
        setFormParent('');
        return;
      }
    
      setAdding(true);
      const newTerm = await addTerm({
        name: formName,
        parent: formParent ? formParent : undefined,
      });
      const defaultName = slug === 'category' ? (0, external_wp_i18n_namespaceObject.__)('Category') : (0, external_wp_i18n_namespaceObject.__)('Term');
      const termAddedMessage = (0, external_wp_i18n_namespaceObject.sprintf)(
        /* translators: %s: taxonomy name */
        (0, external_wp_i18n_namespaceObject._x)('%s added', 'term'),
        (_taxonomy$labels$sing = taxonomy?.labels?.singular_name) !== null &&
          _taxonomy$labels$sing !== void 0
          ? _taxonomy$labels$sing
          : defaultName
      );
      (0, external_wp_a11y_namespaceObject.speak)(termAddedMessage, 'assertive');
      setAdding(false);
      setFormName('');
      setFormParent('');
      onUpdateTerms([...terms, newTerm.id]);
    } catch ( error ) {
        // I want to show the snack bar here instead of the Notice in the Editor.
        const errorMessage = error.message || 'An error occurred';
        createErrorNotice(errorMessage);
    }
  };
0

There are 0 best solutions below