next-routes
next-routes copied to clipboard
Can't get query to pass through root component
// ./_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.
Did you find your error ? i'm facing the same issue
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
Maybe you should try a different approach. https://github.com/zeit/next.js/#fetching-data-and-component-lifecycle
Maybe this can help you.
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