0

I'm using react-query, when I get the id from the url and try to call it inside getSubject, it passes an undefined value http://localhost:3000/api/subject/undefined

but when I click a link from another component to get in this subject component it works but if refresh the page it does not work.

  const router = useRouter()

  const { id } = router.query

  const { data } = useQuery('subjects', async () => await getSubject(id))

  return value...
}
Ahmed Ibrahim
  • 477
  • 1
  • 7
  • 18
  • 1
    Does this answer your question: [Conditionally calling an API using React-Query hook](https://stackoverflow.com/questions/63397534/conditionally-calling-an-api-using-react-query-hook)? You can use [Dependent Queries](https://react-query.tanstack.com/guides/dependent-queries) so the query is only run if `id` is set, i.e. `{ enabled: !!id }`. – juliomalves Sep 25 '21 at 15:29

1 Answers1

1

You should use getServerSideProps in this case. It has access to query params. On top of that you can prefetch data on the server side too.

export interface PageProps {
  id: string;
}

export function Page({ id }: PageProps ) {
  const { data } = useQuery('subjects', async () => await getSubject(id))
}

export const getServerSideProps: GetServerSideProps<PageProps > = async ({
  params,
}) => {
  const { id } = params;

  return {
    props: {
      id,
    },
  };
};

If you still want to use router, you can wait for router.isReady flag. When it is true, query params should be parsed.