Uncaught TypeError: Cannot read property 'source' of undefined

Hi all,
I am building my WikiPedia Viewer but I have this issue:

On this line:

I do not get it? Here is my project:

I’ve been working on this for a while and I do not know how to sort this out. Can someone offer me a clue?

Thanks as always!!

If you look at the response you get back some of the pages does not have the thumbnail property. Make a check for the property before trying to access it.

Missing thumbnail property

ns: 0
pageid: 26929
title: "Spanish"

Has thumbnail property

ns: 0
pageid: 925767
pageimage: "Escudo_de_España_(mazonado).svg"
thumbnail: {source: "https://upload.wikimedia.org/wikipedia/commons/thu…50px-Escudo_de_Espa%C3%B1a_%28mazonado%29.svg.png", width: 50, height: 50}
title: "Elections in Spain"

I get what you mean but not sure how I would go about putting this into code - I need to check the property before I access it right?

Yes. You can check that response.query.pages[key].thumbnail gives you a Truthy value.

  1. When using an if statement and a variable declared with let, you need to remember to declare the variable outside the if statement, otherwise it will be scoped to the if.
const key = Object.keys(response.query.pages);
let imgUrl = ''; // with a default value

if (response.query.pages[key].thumbnail) {
  imgUrl = response.query.pages[key].thumbnail.source;
  1. I would probably use a ternary.
const key = Object.keys(response.query.pages);
const imgUrl = response.query.pages[key].thumbnail ? response.query.pages[key].thumbnail.source : '';
  1. A ternary, placeholder image and some destructuring.
const key = Object.keys(response.query.pages);
const noImage = "https://via.placeholder.com/400"
const { thumbnail } = response.query.pages[key];
const imgUrl = thumbnail ? thumbnail.source : noImage;
1 Like

Thanks I am going to try this. Cheers!!!

Thanks again for this, I get it now but I have noticed something, it should the placeholder now even if I click through and there is a thumbnail but not on all!? Strange right.

Thanks again :slight_smile:

The pageimages prop is not guaranteed to return an image. It also has a license param (pilicense) that by default it is set to ‘free’ if you set it to ‘any’ you should get some more images back.

pilicense: 'any'

This page (Audi_A3) has images but they are not part of the response when using pageimages

Api Sandbox for Audi_A3 page (click the Make request button)

To make sure you always get an image (if the page has one) you need to use the images prop. To get the actual image URL you will have to make another API call using the image name.

Api Sandbox main image on the Audi_A3 page (click the Make request button)

Some more info

Doing either or (use thumbnail if it exists otherwise image) is definitely more work.

1 Like

Let go over this with my project and get back to you. Cheers for help :slight_smile: