Sure! Here's an example code snippet for a Next.js page that fetches the JSON data from the Walla News API and displays the title and description on the page:
javascriptimport { useRouter } from 'next/router';
import Head from 'next/head';
function ArticlePage({ title, description }) {
const router = useRouter();
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<Head>
<title>{title}</title>
</Head>
<h1>{title}</h1>
<h2>{description}</h2>
</div>
);
}
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
};
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://dal.walla.co.il/event/${params.id}`);
const { data } = await res.json();
return {
props: {
title: data.title,
description: data.description,
},
revalidate: 60, // seconds
};
}
export default ArticlePage;
Here's how it works:
- The
getStaticPaths
function returns an empty array of paths and sets thefallback
option totrue
, which means that Next.js will generate the page on the fly when a user visits it for the first time. - The
getStaticProps
function takes theid
parameter from the URL and uses it to fetch the JSON data from the Walla News API. It then extracts thetitle
anddescription
fields from the data and passes them as props to theArticlePage
component. - The
ArticlePage
component displays the title and description inh1
andh2
tags, respectively. It also sets the title of the page using theHead
component from Next.js. - If the page is still being generated (
router.isFallback
istrue
), the component displays a loading message.
To use this code, save it in a file called [id].js
under the pages
directory of your Next.js project. Then, you can visit the article page by navigating to http://localhost:3000/[id]
, where id
is the ID of the article you want to display. For example, to display the article with ID 3572205, you would navigate to http://localhost:3000/3572205
.