• Resolved aboutsam

    (@aboutsam)


    Hey guys, four months ago i created a block component which use useEffect() to listen to __experimentalSetPreviewDeviceType()

    useEffect(() => {
    let viewport;

    if (select('core/edit-site')) {
    viewport = select('core/edit-site').__experimentalGetPreviewDeviceType();
    }

    if (select('core/edit-post')) {
    viewport = select('core/edit-post').__experimentalGetPreviewDeviceType();
    }
    }, []);

    This code not work anymore for some reason. Is there any changes to device type?

    I want that my component will listen to __experimentalGetPreviewDeviceType(), how i can do that?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Stef

    (@serafinnyc)

    Hello @aboutsam see if this works

    useEffect(() => {
    let viewport;

    const updateViewport = () => {
    if (select('core/edit-site')) {
    viewport = select('core/edit-site').__experimentalGetPreviewDeviceType();
    }

    if (select('core/edit-post')) {
    viewport = select('core/edit-post').__experimentalGetPreviewDeviceType();
    }

    console.log(viewport); // You can use this to see the current viewport value
    };

    // Listen for changes in the editor's state
    const unsubscribe = subscribe(updateViewport);

    // Cleanup the subscription
    return () => unsubscribe();
    }, []);
    Thread Starter aboutsam

    (@aboutsam)

    Hey @serafinnyc, i got this message:

    ReferenceError: subscribe is not defined
    at _viewport.js:90:23

    where do I have to import it?

    Thanks so far!

    Stef

    (@serafinnyc)

    Sorry @aboutsam I just assumed you left out the import parts. Your code should look like this.

    import { useEffect } from '@wordpress/element';
    import { select, subscribe } from '@wordpress/data';

    useEffect(() => {
    let viewport;

    const updateViewport = () => {
    if (select('core/edit-site')) {
    viewport = select('core/edit-site').__experimentalGetPreviewDeviceType();
    }

    if (select('core/edit-post')) {
    viewport = select('core/edit-post').__experimentalGetPreviewDeviceType();
    }

    console.log(viewport); // You can use this to see the current viewport value
    };

    // Listen for changes in the editor's state
    const unsubscribe = subscribe(updateViewport);

    // Cleanup the subscription
    return () => unsubscribe();
    }, []);
    Thread Starter aboutsam

    (@aboutsam)

    Thanks you @serafinnyc, that’s exactly what I was looking for!

    Stef

    (@serafinnyc)

    You’re welcome @aboutsam

Viewing 5 replies - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.