skip to Main Content

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.

2

Answers


  1. 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 🙂

    Login or Signup to reply.
  2. You can acheave this using two methods:

    1. URL Parameters or Query Strings.
    2. Next.js API Routes for Server-Side Data Fetching.

    1. URL Parameters or Query Strings.

    In Filter.jsx:

    const router = useRouter();
    
    const handleSubmit = async () => {
      const filteredData = await fetchFilteredData();
      router.push({
        pathname: '/test',
        query: { subject: filteredData.subject, grade: filteredData.grade }, // Example query parameters
      });
    };
    

    Test.jsx:

    import { useRouter } from 'next/router';
    
    const Test = () => {
      const router = useRouter();
      const { subject, grade } = router.query;
    
      // Use subject and grade as needed
    };
    

    2. Next.js API Routes for Server-Side Data Fetching.

    In filter.jsx:

    const handleNavigate = () => {
      router.push(`/test?id=${filteredDataId}`);
    };
    

    Test.jsx:

    export async function getServerSideProps(context) {
      const { id } = context.query;
      const data = await fetchFilteredDataById(id);
      return { props: { data } };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search