Home > Net >  Image src changes when i update the image but frontend displays the old image
Image src changes when i update the image but frontend displays the old image

Time:06-09

I have found weird bug in my application. I am using VueJS3 and typescript. I am creating a media gallery, where users can manage assets. All endpoints and backend side of application works perfectly. Currently i am working on updating image files(updating image field). My code works in theory, image url updates to a new one, but even the url is newer, image that is rendered is old image(before update). When i try to view my application in incognito window, my newer image is showing. But it does not work otherwise(works if and only user clears his cache) I hope i explained myself clearly, it is a little complicated :)

When i fetch the data from api, they don't have any src, so i have to create a property when using the data. Here is the code below.

const { res, err } = await this.$api.image.getAll(params)
res.data.items.forEach(async (image: Image<Populated>) => {
   image.src = this.$fileHandler(image._id)
})

Note: File handler is a special method that gives the image source by id

CodePudding user response:

Apparently your assets get cached, and there are multiple ways to solve that.

Not diving too much into caching strategies and cache control tags, just do

image.src = `${this.$fileHandler(image._id)}?_=${ new Date()}`

This will generate a unique (almost) URL for your image, invalidating every previous cached one.

  • Related