next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

Can't get query to pass through root component

Open corysimmons opened this issue 5 years ago • 4 comments

// ./_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.

corysimmons avatar Feb 21 '19 18:02 corysimmons

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

remyzv avatar Mar 14 '19 18:03 remyzv

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

  • https://nextjs.org/learn/basics/clean-urls-with-route-masking
  • https://nextjs.org/learn/basics/server-side-support-for-clean-urls/create-a-custom-server

corysimmons avatar Mar 15 '19 02:03 corysimmons

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

Maybe this can help you.

abnersajr avatar Mar 29 '19 21:03 abnersajr

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

chmelevskij avatar Apr 06 '19 06:04 chmelevskij