javascriptnode.jsreact-nativegoogle-cloud-platform

Error: Cannot create URL for blob! when converting blob to URL in react native


So I am fetching an image using the google places photos API, I created a request on Postman and i get back the image in a jpeg format, here are headers:

Postman headers received

When I make the same request on my react native app I get the error [Error: Cannot create URL for blob!]. I tried logging the data after hitting await response.blob() and i get back this:

{"_data": {"__collector": {}, "blobId": "88865B74-7358-4D4C-BDBA-786330A6CE5D", "name": "2022-12-09.jpg", "offset": 0, "size": 36317, "type": "image/jpeg"}}

So it all looks good but why can't i get a URL from this blob?

const [image, setImage] = useState<string>();

  useEffect(() => {
    const fetchImage = async () => {
      try {
        const response = await fetch(
          "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photo_reference=[PHOTO_REFERENCE]key=[API_KEY]"
        );
        const data = await response.blob();
        console.log(data);
        setImage(URL.createObjectURL(data));
      } catch (e) {
        console.log(e);
      }
    };
    fetchImage();
  }, []);

The line that causes the error is setImage(URL.createObjectURL(data));


Solution

  • I just saw this answer from another community member about the URL.createObjectURL function not working with React Native:

    The URL.createObjectURL function is not available in React Native because React Native does not use a browser environment like traditional web applications. Instead, it uses a combination of JavaScript and native components to render the user interface.

    In React Native, you typically work with local image files or remote URLs directly, rather than creating object URLs.

    Maybe you could use alternatives mentioned in this post1 & post2, such as converting the data into base64 string or using React Native-compatible libraries like react-native-blob-util, rn-fetch-blob, or react-native-fetch-blob, which are also listed in the React Native Directory.

    You can also check this issue posted on Github, which might give you insights.