Skip to content
Advertisement

React not getting different images for same URL

I am making a users page with arbitrary data and noticed that since the image URL is the same (https://source.unsplash.com/random) the image is the same. How can I prevent this?

application screenshot

Advertisement

Answer

That is because, your browser caches your url and assumes you are hitting the same url so it populates previous result. Add a random query to the url like source.unsplash.com/random?v={random_number_here} will solve your problem

This has nothing to do with react.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="images-wrapper"></div>

    <script>
const wrapper = document.getElementById('images-wrapper');
var html = '';
// for(var i =0;  i< 10; i++){  // same images
// html += '<img src="https://source.unsplash.com/random">';
// }
for(var i =0;  i< 10; i++){ // different images
html += '<img src="https://source.unsplash.com/random?v='+(i+1)+'">';
}
wrapper.innerHTML = html;

    </script>
</body>
</html>
Advertisement