I am using the WordPress components in the admin panel of my plugin 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 a 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;
    },
    [id]
  );

  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 null.

What can I do to make retrieving the image information work?
Similar code in the Gutenberg editor works…

0

Leave a Reply

Your email address will not be published. Required fields are marked *