I have this problem that the GIPHY API always returns the same results. And I'm quite sure this is not because I somehow store the previous result and post it again and again. For example, I type in 'dog' and ask for 5 results .. I get 5 dog gifs, then I refresh the page and repeat the process and get exactly the same gifs.
Is there an elegant solution to get random gifs every time I make a request?
The solution I thought of is: when I make a repeated request, I would request (under the hood) for 10 gifs and then would post on the page from these new 10 gifs just the 5 new ones but this solution can get quite messy when the amount of gifs needed will get larger.
Here's my code so far:
<v-container>
<v-layout text-center wrap>
<v-flex xs12>
<v-img :src="require('../assets/logo.svg')" class="my-3" contain height="200"></v-img>
</v-flex>
<v-text-field label="Search" outlined rounded v-model="searchText"></v-text-field>
<v-btn outlined rounded block @click="findGIF">Search</v-btn>
<div class="gifs" v-show="showGIFs" ref="gifs">
<div v-for="(gif, index) in gifs" :key="index">
<img class="gif" :src="gif.preview" />
</div>
</div>
</v-layout>
</v-container>
</template>
<script>
export default {
data: function() {
return {
searchText: "",
gifs: [],
index: 1,
showGIFs: true
};
},
methods: {
async fetchGIFs(number) {
let apiKey = "myKey"; // deleted to keep it private
let searchEndPoint = "https://api.giphy.com/v1/gifs/search?";
let limit = number;
let gifsArray = [];
let url = `${searchEndPoint}&api_key=${apiKey}&q=${this.searchText}&limit=${limit}`;
try {
let response = await fetch(url);
let json = await response.json();
json.data.forEach(gif => {
gifsArray.push({
url: gif.url,
preview: gif.images.preview_gif.url,
src: gif.images.original.url,
height: gif.images.original.height,
width: gif.images.original.width
});
});
return gifsArray;
} catch (error) {
console.log("Ooops, take a look at this error: " + error);
}
return "I guess something didn't go right here";
},
findGIF() {
let temp = [];
(async () => {
try {
temp = await this.fetchGIFs(5);
this.gifs.push(...temp);
} catch (err) {
console.log("Have a look at this: " + err);
}
})();
}
}
};
</script>
Thank you!