skip to Main Content

I want to display the images of a particular product. I am fetching the images of a product and the images path is printing correctly in the console but the images does not display in the page.
Is there some other method to do it?
ProductImage.jsx

import axios from 'axios';
import React, { useEffect, useState } from 'react'

export default function ProductImage({product_id}) {

  const [images, setImages] = useState([]);

  useEffect(() => {
    (async () => {
      const {data} = await axios.get(`products/${product_id}/images`);
      setImages(data);
      data.map((image) => {
        console.log(image.image);
      })
    })();
  }, []);

  return (
    <div>
      {images.map((image) => {
        return <img key={image.id} src={image} alt="some-image" />
      })}
    </div>
  )
}

3

Answers


  1. src={image}
    

    src needs to be a url, currently you are passing it what looks like an object image

    Try logging just image to see what key holds the url, then you can set it. For example if the image’s path is in image.image:

    src={image.image}
    

    BTW data.map is the wrong method to use – if you just want to loop through the data use data.forEach

    Login or Signup to reply.
  2. {images.map((image) => {
       return <img key={image.id} src={image.image} alt="some-image" />
    })}
    

    Based on your image object, I think this is the right way to do it

    Login or Signup to reply.
  3. Try :

    src={`${URL.createObjectURL(image?.image)}`}
    

    or,

    src={`${rootUrl}${image?.image}`}
    

    Here, rootUrl looks like "192.168.31.183:8000"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search