Dhenyson Jhean
Dhenyson Jhean

Reputation: 824

Check Image URL before updating State in React / Next

The logic below is in: React / Nextjs with styled-components.

Hello, I have a component that "renders" a blog banner (background-image), the url comes from a state that already has a standard image.

const [blogBanner, setBlogBanner] = useState ('/ images / imageBlogDefault.png')

But before the component receives this state, the code checks whether that blog already has a user-defined banner. If so, then take the url and update the state.

if (props.blog.image) {
    setBlogBanner (`$ {hlp.BACKEND_HOST} / images / blogBanners / $ {props.blog.image}`)
}

And in styled-components I use background-image: url (blogBanner).

The problem is that the request that takes the blogs returns only the banner url and not the image itself, so if for some reason the image is deleted from the database without removing the url from it on the blog ... when loading this blog my code will "understand" that blog "has an image" and will update the state with the new url.

So what I need is that in addition to checking if it has a url (as I already do), I need to check if that url returns an image before updating the state, but I don't know how to do that. It could even be with css (styled-component) if it were possible.

I tried to create a function that takes the image url and makes an HTTP request, if it returns status 404 then I did not update the state of the url. But it did not work. Is there any direct treatment in the React components?

Upvotes: 0

Views: 744

Answers (1)

dave
dave

Reputation: 64695

You could do:

var image = new Image();
image.onload = () => setBlogBanner(image.src)
image.src = `$ {hlp.BACKEND_HOST} / images / blogBanners / $ {props.blog.image}`

which will preload the image, and if it loads successfully, you set the blog banner value to that src.

Upvotes: 1

Related Questions