Skip to main content

Fetch a Random Wikipedia Post

// random.jsx
const Random = ({ id, thumbnail, title }) => {
let img = null;

if (thumbnail) {
img = (
<img alt={title} src={thumbnail.source} />
);
}

return (
<section>
<header>
<h1>{title}</h1>
</header>

<p>Article id: {id}</p>

{!img && <em>No picture for given article.</em>}
{img}

<p>
<a
href={`https://en.wikipedia.org/wiki/${encodeURI(title)}`}
target="_blank"
>Read full article</a>
</p>
</section>
);
};

const fetchImage = async ({ id, title }) => {
const request = await fetch(
'https://en.wikipedia.org/w/api.php?' +
'action=query&' +
'format=json&' +
'prop=pageimages&' +
`titles=${encodeURI(title)}&` +
'pithumbsize=100',
);
const results = await request.json();
const thumbnail = results.query.pages[id].thumbnail;

return thumbnail || null;
};

export const getStaticProps = async () => {
const article = {
id: null,
thumbnail: null,
title: null,
};
const request = await fetch(
'https://en.wikipedia.org/w/api.php?' +
'action=query&' +
'format=json&' +
'list=random&' +
'rnnamespace=0&' +
'rnlimit=1&' +
'prop=pageimages&'
);
const results = await request.json();
const post = results.query?.random[0];

article.id = post.id;
article.title = post.title;
article.thumbnail = await fetchImage(article);

return {
props: article,
};
};

export default Random;