how to pass data from one page to another page in Next.js?

Viewed 3026

I am stuck with a problem with passing data from one page to another page in next.js as I am building a basic news application in which I am fetching get requests from news api and I got results of 10 articles and I mapped them correctly but I want to pass the single article date to a new Page named singleNews. So How can I do it? here is place where I am fetching all 10 articles:

export default function news({data}) {
    // const randomNumber = (rangeLast) => {
    //   return  Math.floor(Math.random()*rangeLast)
    // }
    // console.log(data)

    return (
        <>
        <div>
            <h1 className="heading">Top Techcrunch Headlines!</h1>
        </div>
        <div className={styles.newsPage}>
            { // here you always have to check if the array exist by optional chaining
             data.articles?.map(
                (current, index) => {
                    return(
                        <Card datas={current} key={index+current.author} imageSrc={current.urlToImage} title={current.title} author={current.author}/>
                    )
                }
            )
        }
        </div>
        </>
    )
}

export async function getStaticProps() {
    const response = await fetch(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${process.env.NEWS_API_KEY}&pageSize=12`)
    const data = await response.json() // by default Article length is 104
    // const articles =  data.articles;

    return{
        props : {
            data,
        }
    }
}
1 Answers

You can pass data to another page via Link component this way:

import Link from 'next/link'

<Link
  href={{
    pathname: '/to-your-other-page',
    query: data // the data
  }}
>
  <a>Some text</a>   
</Link>

and then receive that data in your other page using router:

import { useRouter } from 'next/router'
const router = useRouter();
const data = router.query;

Let me know if that helps.

Related