Skip to content
Advertisement

Displaying images from fetch API call Node/React

Im trying display images im fetching from API btw url is defined

fetch(url).then((res) => {
            res.blob()
            .then((img) => {
                console.log(img)
                const  objectURL = URL.createObjectURL(img);
                const url = objectURL.replace(/[blob:]{5}/gi,'')
                ReactDOM.render(<Gallery photos={url} />, document.getElementById('root'));
     });
})

Gallery.js

import React, { Component } from 'react';

class Gallery extends Component {
  constructor (props) {
    super(props);
    this.state = {
      Images: []
    }
  }

  componentDidMount () {
    this.setState({images: this.props.photos});
  }
  render() {
    const {image} = this.props.photos;
    return (
      <div >
          <img 
              className="App"
              width="300"
              height="300"
              src={image} 
              alt="dogs"/>
      </div>
    );
  }
}

export default Gallery;

with or without the regex /[blob:]{5}/gi it is only displaying the alt prop and not the image. The image is received and the get call is successful but the objectURL url is not working. Any help?

Advertisement

Answer

const {image} = this.props.photos; is equivalent to

const image = this.props.photos.image;

It means, “assign the property image of this.props.photos to the variable image.

However, this.props.photos is a string. Strings don’t have a image property. You simply want

const image = this.props.photos;

You are not doing anything with this.state.Images, so you can remove the constructor and componentDidMount.


/[blob:]{5}/gi doesn’t do what you want it to do. It means “match all sequences of 5 characters that consist of b, l, o or :

I.e. the character sequence bb:ol would match.

If you wanted to remove the sequence blob: at the beginning of the string, then you should be using /^blob:/i instead.

However, you shouldn’t remove blob: from the URL.


Complete and simplified example

import React, { Component } from 'react';

function Gallery(props) {
  return (
    <div >
      <img 
        className="App"
        width="300"
        height="300"
        src={props.image} 
        alt="dogs"
      />
    </div>
  );
}

fetch(url)
  .then(res => res.blob())
  .then(img => {
    ReactDOM.render(
      <Gallery image={URL.createObjectURL(img)} />,
      document.getElementById('root'),
    );
  })
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement