Trying to load a dynamic path for image using React useEffect and useState from node.js server

1.7k views Asked by At

I am trying to load an image from a fetch done from a server. Images are saved in an assets folder on the front end. I end up getting: " Error: Cannot load module './' " I assume it is because the state is not populated when trying to return the HTML. When I load just the path name, it works, but not when trying to load the img? Any help to a self taught coder would be helpful.

    export default function PlaceBids(props) {

    const [quoteImage, setQuoteImage] = useState('')
    useEffect(() => {
        fetch('/api/bids?bids=' + props.quoteNumber, {
            credentials: 'same-origin',
        })
            .then(res => res.json())
            .then((res) => {
                if (res.loggedIn === false) {
                    return null
                }
                if (res.success) {
                    setQuoteImage(res.quoteImage)
                }
                else {
                    setQuoteImage(res.quoteImage)
                }
            }
            )
    }, [])

return (
   <div>
     <img src={require('../assets/models/' + quoteImage)}/>
   </div>
)
}
1

There are 1 answers

0
Jay On

This is what I would try.

//pass your api response to this

function ShowImage({ data }) {
    return (
        <div className="ShowImage">
          <img src={data.quoteImage} alt={"showing image here from api "}  />
        </div>
      );
}

This is how I would handle a simple image display in react JS. If you had (or could) put your code in a codesandbox or something, perhaps, I could test if this really works for you.

essentially, since, I am getting the full image URL from API, I bypass the local folder.

Render # 1

image will render, but there is no image, so it will simply say "showing image here form api".

then, useEffect will call the API, and when API succeeds, it trigers a state change and calls for render again, but this time, you are sending your API response.

Render # 2

Image renders using the image path at data.quoteImage.

note : I am assuming it is a simple case of image display, for I am also a beginner. However, if this is something far more complicated, then, others in the community should be able to help you out.