Using the Tenor GIF Api. I get this error, only about 10% of the time, the other 90% it works:
caught TypeError: Cannot read properties of undefined (reading ‘media_formats’)
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
var index = getRandomInt(10);
var image = document.getElementById("share_gif");
image.src = top_10_gifs[index]["media_formats"]["gif"]["url"];
var dimX = top_10_gifs[index]["media_formats"]["gif"]["dims"][0];
var dimY = top_10_gifs[index]["media_formats"]["gif"]["dims"][1];
return;
it throws the error where it tries to read the first [‘media_formats’], saying it can’t read undefined.
The object is loaded however, if I console.log the object right before that line it will have an object. For some reason, only a small percentage of times, it is undefined.
Not sure why it’s doing that. Thanks
2
Answers
I used the example from the docs and they were spot on: https://developers.google.com/tenor/guides/quickstart
I got an undefined error because I was grabbing 8 GIFs and then using a random number to choose one of those GIFs. The random number was 0-9, so when it chose 9 it would return undefined.
Sorry for the noob question
You can use a function like this to select a pseudorandom element from an array:
Below is a code sample to help. It uses a payload that was obtained by using the example query in the API docs at the Trending GIFs endpoint.
Be sure to read the API documentation to understand the structure of the responses.