Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next.js useRouter() query: { amp: undefined } #8051

Closed
tsoisauce opened this issue Jul 22, 2019 · 10 comments
Closed

Next.js useRouter() query: { amp: undefined } #8051

tsoisauce opened this issue Jul 22, 2019 · 10 comments

Comments

@tsoisauce
Copy link

tsoisauce commented Jul 22, 2019

I am having issues passing in query objects to useRouter() hook. I am attempting to capture URL params and pass it into a page component pages/post.js server-side using koa. and koa-router.

I am using Koa.js as my middleware based on next.js example: custom-koa-server
and using Next's documentation: Custom routes (using props from URL)

// server.js

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  router.get("/post/:slug", async ctx => {
    await app.render(ctx.req, ctx.res, "/post", { slug: ctx.params.slug });
    ctx.respond = false;
  });

  router.get("*", async ctx => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(async (ctx, next) => {
    ctx.res.statusCode = 200;
    await next();
  });

  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});
// pages/post.js

import { useRouter } from "next/router";

const Post = () => {
  const router = useRouter();
  console.log(useRouter());
  const { slug } = router.query;

  return <p>My Blog Post: {slug}</p>;
};

export default Post;

useRoute() console.log

// output: console.log(useRoute());

ServerRouter {
  route: '/post',
  pathname: '/post',
  query: { amp: undefined },
  asPath: '/post/testing' }

When attempting to access the query object, no matter what, I get { amp: undefined }

Any help on this will be super helpful! Thank you in advance!

@Timer
Copy link
Member

Timer commented Jul 22, 2019

Hi! Questions belong on our Spectrum, please open a support request there with a reproduction repository.

Also, in your provided code I don't see the need for a custom server, dynamic routes would fulfill your needs:
https://nextjs.org/docs#dynamic-routes

@Timer Timer closed this as completed Jul 22, 2019
@tsoisauce
Copy link
Author

tsoisauce commented Jul 22, 2019

@Timer Thanks! Apologies for the misplacement...issue posted here

oh and the reason why I am not using Dynamic Routes is that this will eventually be a server-side fetch to an API and passed rendered into a page component. Details in the General Channel of Next.js Spectrum.

@Timer
Copy link
Member

Timer commented Jul 22, 2019

Does getInitialProps not support what you're trying to do?

@jingyuanhe
Copy link

i have the same problem,How did you solve it

@chanced
Copy link

chanced commented Jan 30, 2020

@jingyuanhe

All you need to do to resolve this is useEffect to make sure it runs after router has initialized.

For example:

  const [queryId, setQueryId] = useState(null)
  useEffect(()=> {
    if(router && router.query) {
      setQueryId(router.query.id)
    }
  }, [router])

@bduffany
Copy link
Contributor

It seems a bit user-unfriendly that the router.query is not properly initialized until first render. What's the technical reasoning behind this?

@denvaar
Copy link

denvaar commented Apr 29, 2020

This is the workaround I used:

const queryString = require('query-string'); // https://www.npmjs.com/package/query-string
const { filters } = queryString.parse(router.asPath.substring(1));

I noticed that router.query was missing the query params as my component was re-rendered, but they were correct on router.asPath. I parse the params manually from that instead.

@codefist
Copy link

It seems a bit user-unfriendly that the router.query is not properly initialized until first render. What's the technical reasoning behind this?

There can't be a good reason, it's a bug. The returning of the router object SHOULD block by default, or we should be able to configure it to block until the query attribute has been set.

@samipshah100
Copy link

samipshah100 commented Nov 20, 2020

Had the same issue with type-in urls. Waiting in useEffect for router.query to be initalized first sovled my problem.
https://nextjs.org/docs/advanced-features/automatic-static-optimization

@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 29, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants