Prompt Title: Next.js Article Page.

Created 1 year ago
Votes 0
Views 127 times
0
Human: i need you to create me a next.js article page that gets json from api https://dal.walla.co.il/event/3572205 for article id 3572205. 1. make the title inside the data as H1, 2. make the description inside the data as H2.
ChatGPT:

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:

javascript
import { 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 the fallback option to true, 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 the id parameter from the URL and uses it to fetch the JSON data from the Walla News API. It then extracts the title and description fields from the data and passes them as props to the ArticlePage component.
  • The ArticlePage component displays the title and description in h1 and h2 tags, respectively. It also sets the title of the page using the Head component from Next.js.
  • If the page is still being generated (router.isFallback is true), 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.

avatar
Antonio
Shared 4 prompts
Created 1 year ago

Leave a Comment