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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.