Search code examples
javascriptreactjsnext.js

How can I send data between two pages in Next.js?


The specific case is that I use one page filter.jsx to get the request from the user like the subject, the grade of student, the difficulty level, ... Then I process them via an API filter/route.js to filter the question database and send the filtered data back to the page filter.jsx.

How can I create a button in filter.jsx that when clicked will move to other page test.jsx and use the filtered data in this test.jsx page?

I used Link and router.push but they dont work. Maybe I was using it the wrong way.


Solution

  • There are a number of ways you could do this. One would be to use URL parameters in the <Link> from the filter.jsx page to test.jsx, like

    const filterValue = "some-value";
    ...
    href={`/whatever/url/test-is-at?filter=${filterValue}`}
    ...
    

    Then you can get this in the test.jsx page via

    Next 14:

    export default function Page() {
        const searchParams = useSearchParams();
        const filterValue = searchParams.filter;  // some-value
    ...
    

    https://nextjs.org/docs/app/api-reference/functions/use-search-params

    Next 13:

    export default function Page({searchParams}) {
        const filterValue = searchParams.filter;  // some-value
    ...
    

    https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional

    Probably your filter value is in state so that when your API call resolves, you set the state and it updates the href in your Link, but you probably knew that already :)