Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wp.data.subscribe properly

How to use wp.data.subscribe to Show/Hide a block for a certain Post Format (Audio, Video, and Gallery), I test this code and it's working good BUT it triggered while writing the post content and when select any other option so the target block flicker while writing.

wp.data.subscribe(() => {

    var postFormat = wp.data.select('core/editor').getEditedPostAttribute('format');


    $('#blockAudio, #blockVideo, #blockGallery').hide();


    if( postFormat == 'gallery' ) {

      $('#blockGallery').fadeIn();

    }

});
like image 935
Hady Shaltout Avatar asked Sep 12 '18 18:09

Hady Shaltout


1 Answers

wp.data.subscribe is a wrapper around Redux's store.subscribe.

From the Redux docs:

subscribe(listener) adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState() to read the current state tree inside the callback.

My interpretation: wp.data.subscribe is, by design, called every single time a change occurs in the current state. While editing posts in the editor, the state is changed enumerable times, so it makes sense that the listener function is called every single time. My bet is that you should check yourself if a relevant part of the state has changed, and then do the thing you want.

So I think you could modify your code something like this:

const getPostFormat = () => wp.data.select('core/editor').getEditedPostAttribute('format');

// set the initial postFormat
let postFormat = getPostFormat();

wp.data.subscribe(() => {

    // get the current postFormat
    const newPostFormat = getPostFormat();    

    // only do something if postFormat has changed.
    if( postFormat !== newPostFormat ) {

      // Do whatever you want after postFormat has changed
      if (newPostFormat == 'gallery') {
        $('#blockAudio, #blockVideo, #blockGallery').hide();
        $('#blockGallery').fadeIn();
      }

    }
    
    // update the postFormat variable.
    postFormat = newPostFormat;

});

Sources:

  • https://redux.js.org/api/store/#subscribelistener

  • https://developer.wordpress.org/block-editor/packages/packages-data/#generic-stores

like image 163
Jules Colle Avatar answered Oct 24 '22 03:10

Jules Colle