Plugin Development – Using the component outside the editor. select(‘core’) is null

I’m using wordpress components in my plugin’s admin panel and trying to make an image upload button. The button works fine and allows me to select an image, but when I select an image, I get an error in the console::

An error occurred while running ‘mapSelect’: Cannot read properties of Null (reading ‘getMedia’) The error may be correlated with this previous error: TypeError: Cannot read properties of Null (reading ‘getMedia’)

My Component:

import { useSelect } from '@wordpress/data';
import { MediaUpload } from '@wordpress/media-utils';
import { Button, ResponsiveWrapper } from '@wordpress/components';

export default ({ onSelect, id }: { onSelect: (id: number) => void; id?: number }) => {
  const media = useSelect(
    (select) => {
      return id ? select('core').getMedia(id) : undefined;
    },
    https://wordpress.stackexchange.com/q/403859
  );

  const onSelectMedia = (selectedMedia) => {
    onSelect(selectedMedia.id);
  };

  return (
      <MediaUpload
        onSelect={onSelectMedia}
        allowedTypes={['image']}
        value={id}
        render={({ open }) => (
          <Button onClick={open} variant="secondary">
            {!id && 'Select image'}
            {media && (
              <ResponsiveWrapper naturalWidth={media.media_details.width} naturalHeight={media.media_details.height}>
                <img src={media.source_url} alt={media.alt} />
              </ResponsiveWrapper>
            )}
          </Button>
        )}
      />
  );
};

console.log(select('core')) In useSelect returns zero.

What can I do to retrieve image information? Same code works in Gutenberg editor…

Leave a Comment