3

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

1
  • I'm having the same issue. Did you end up finding a solution?
    – donnapep
    Commented Mar 31, 2022 at 1:22

1 Answer 1

1

I hope you found the answer, but for anyone else wondering: You need to tell WordPress what scripts to enqueue. When you compile your React code, at least if you use WordPress' native solution, a file named [filename].assets.php is automatically created in the build folder. When you register the script for the options page in your plugin file, you can add this to the dependencies, like so:

$assets = require PLUGIN_PATH . 'build/[filename].asset.php';

wp_enqueue_script(
  'options-page-script',
  PLUGIN_URL . '/build/[filename].js',
  $assets['dependencies'],
  '1.00',
  true
);

Alternatively you can keep track of the handles of the scripts, and add them manually, like so:

wp_enqueue_script(
  'options-page-script',
  PLUGIN_URL . '/build/[filename].js',
  ['wp-components', 'wp-element'], // <-- Change this to what you need
  '1.00',
  true
);

For the media uploader to work, you might also need to run wp_enqueue_media(), but I'm not sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.