Home > Mobile >  How can I show an image with react from an api I created?
How can I show an image with react from an api I created?

Time:12-05

I need to show an image from an api, But it wont show. Im using this.state but it goes directly to the alt image.

I tried with this.state.image it supposed to go to the url_img but it´s not working.

the first_name and last_name are working correctly, it´s renedering in the view ok. so the information from the api is running correctly. It´s just the image

class LastUserInDb extends Component {
  constructor(props) {
    super(props);
    this.state = {
      usuario: [],
    };
  }

  componentDidMount() {
    fetch("http://localhost:3050/usersRoutes/lastUser")
      .then((response) => response.json())
      .then((usuario) => {
        console.log(usuario)
        this.setState({
          apellido: usuario.data.last_name,
          nombre: usuario.data.first_name,
          image: usuario.data.url_img
          
        });
      });
      console.log(this.state.image)
  }

render() {
  return (
    <div className="col-lg-6 mb-4">
      <div className="card shadow mb-4">
        <div className="card-header py-3">
          <h5 className="m-0 font-weight-bold text-gray-800">
            Ultimo usuario creado:<tr></tr>
          {this.state.apellido}, 
          {this.state.nombre}
          </h5>
        </div>
        <div className="card-body">
        
          <div className="text-center">
            
          <img 
          className="img-fluid px-3 px-sm-4 mt-3 mb-4"
          style={{ width: "40rem" }}
          src={"http://localhost:3000"   this.state.image} 
          alt= "foto ultimo usuario"
            />
         
           
          </div>
          <p>
      
          
          </p>
          
        </div>
      </div>
    </div>
  );
}
}


export default LastUserInDb;

this is the api

{
  "data": {
    "url_img": "/images/users/1670121813886dennis buzenitz.jpg",
    "idUsuario": 29,
    "first_name": "Dennis",
    "last_name": "Buzenitz",
    "email": "[email protected]",
    "password": "$2a$10$rdmiLSvCRpuNVlBdU0daLOyVWAaizxpJAO/9Sd0lArdFP1kjfi666",
    "image": "1670121813886dennis buzenitz.jpg"
  }
}

CodePudding user response:

"1670121813886dennis buzenitz.jpg" => There is an espace between "dennis" and "buzenitz", can't this be the problem ?

CodePudding user response:

you should set the src attribute of the img element directly to the URL that the API is returning, which in this case looks like it's /images/users/1670121813886dennis buzenitz.jpg. change the src attribute in your img element:

<img
  className="img-fluid px-3 px-sm-4 mt-3 mb-4"
  style={{ width: "40rem" }}
  src={this.state.image} 
  alt="foto ultimo usuario"
/>
  • Related