Cat API returning 'undefined'

else if(command === ‘kitteh’) {
fetch(‘https://api.thecatapi.com/v1/images/search’, {
headers: {
‘x-api-key’ : ‘MY_KEY_HERE’,
}
})
.then(
function(response) {
response.json().then(function(data) {
console.log(data.url);
const embed = new Discord.MessageEmbed()
.setTitle(‘kitteh :cat:’)
.setImage(data.url)
.setFooter(${message.author.tag} | powered by TheCatAPI (thecatapi.com));
message.channel.send(embed);
});
}
);

This is my code. It is returning ‘undefined in the console’ and the bot is sending an embed with no image, though i’m getting no errors. What’s wrong here?

data that’s being returned is an array. You probably want the first item in the array.

You can use data[0].url, or change function(data) to function([data]) to automatically destructure the array, and assign the first item to data instead.

Better yet, instead of nesting promises, unwrap your code a little, so you can handle error cases more easily.

else if(command === 'kitteh') {
  fetch('https://api.thecatapi.com/v1/images/search', {
    headers: {
      'x-api-key' : 'MY_KEY_HERE',
    }
  })
  .then(function(result) { return result.json(); })
  .then(function([data]) {
    console.log(data.url);
    const embed = new Discord.MessageEmbed()
      .setTitle('kitteh :cat:')
      .setImage(data.url)
      .setFooter(`${message.author.tag} | powered by TheCatAPI (thecatapi.com)`);
    return message.channel.send(embed);
  });
}

This worked! Thank you so much.