fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

Can't get query to pass through root component #287

Closed corysimmons closed 1 year ago

corysimmons commented 5 years ago
// ./_app.js

// ...

const App = ({ Component, pageProps, query }) => (
  <ApolloProvider client={GraphQLClient}>
    <Component {...pageProps} query={query} />
  </ApolloProvider>
)

App.getInitialProps = ({ query }) => {
  return { query }
}

export default App
// ./routes.js
// https://github.com/fridays/next-routes#how-to-use
const routes = require('next-routes')

module.exports = routes()
  .add('article', '/article/:slug', 'article')
// ./server.js
// https://github.com/fridays/next-routes#on-the-server
const next = require('next')
const routes = require('./routes')
const app = next({ dev: process.env.NODE_ENV !== 'production' })
const handler = routes.getRequestHandler(app)

const express = require('express')
app.prepare().then(() => {
  express()
    .use(handler)
    .listen(5000) // port 5000 here since Next runs on 3000
})
// ./pages/article.js
export default ({ query }) => (
  <div>
    <h1>Article</h1>
    <pre>{JSON.stringify(query, null, 2)}</pre>
  </div>
)

I would expect to get some data in article.js, but it just returns nothing. Any ideas what I'm doing wrong?

I just want to get the values of URL params for things like slugs and ids.

remyzv commented 5 years ago

Did you find your error ? i'm facing the same issue

corysimmons commented 5 years ago

No, I just ended up following the NextJS tutorial (which is the same use case—pretty slugs):

abnersajr commented 5 years ago

Maybe you should try a different approach. https://github.com/zeit/next.js/#fetching-data-and-component-lifecycle

Maybe this can help you.

chmelevskij commented 5 years ago

Done some console logging and found that query is not defined, but router is there. So in my setup, something similar to this is working:

// ./_app.js

// ...

const App = ({ Component, pageProps, query }) => (
  <ApolloProvider client={GraphQLClient}>
    <Component {...pageProps} query={query} />
  </ApolloProvider>
)

App.getInitialProps = async ({ Component, ctx, router: { query } }) => {
  let pageProps = {};

  if(Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }
  return ({ pageProps, query })
}

export default App