Reputation: 1177
Here is a small project I'm working through: https://codesandbox.io/embed/rwxookx6po.
I have several divs that have a backgroundImage
property. The url I am hitting is this one: https://source.unsplash.com/collection/1163637/480x480
Every time you visit that url, you will get a new random image from the collection. I thought that because the props aren't changing, I could force my component to update, but that didn't seem to solve the problem:
shouldComponentUpdate(nextProps) {
if (nextProps.image) {
this.forceUpdate();
return true;
}
}
Given I press a button and pass the same image url prop to my component containing the divs with the background images, how can I get the component to reload, giving my divs a new image background?
Upvotes: 1
Views: 3883
Reputation: 328
You can add a timestamp to your updateImage method, like this:
updateImage() {
const width = 480;
const height = 480;
const timestamp = Date.now();
const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?t=${timestamp}`;
return this.props.updateImage(imageURL, width, height);
}
Upvotes: 7
Reputation: 783
It's a complete hack, but I believe the issue is that the browser is caching the result of the request, so isn't going to the url again, by replacing
const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?random=${Math.random()}`;
It now works. (Note it takes like 5 secs or so for the url to change the image it provides)
Upvotes: 4