Next.js: `shallow` not working with dynamic routing

Created on 19 Dec 2018  路  3Comments  路  Source: vercel/next.js

Bug report

When I try to push a new route with the option { shallow: true } it trigger getInitialProps ignoring the option.

The route is a dynamic route (with custom server) it's something like /handling-request/:id/:tab

I need the param tab to get direct to the selected tab, but I also need to update the url when the tab change.

If you have any suggestion/workaround I'm open to new solutions.

That's the code:

handleTabChange = (e, value) => {
    this.setState({ tabIndex: value });
    const { id } = this.props.router.query;

    Router.replace(`/handling-request?id=${id}&tab=${value}`, `/handling-request/${id}/${value}`, {
        shallow: true,
    });
};

(I'm using material-ui-react tabs)

System information

  • OS: macOS 10.14
  • Browser: Chrome
  • Version of Next.js: 7.0.2

Most helpful comment

https://github.com/zeit/next.js/blob/canary/packages/next-server/lib/router/router.js#L208-L212

https://github.com/zeit/next.js/blob/canary/packages/next-server/lib/router/router.js#L370-L377

Shallow routing works by matching the href's path to a page inside the pages directory to the current page that's rendered. If they're the same page shallow will be used, if not we do a normal router.push/router.replace.

You can read more on how the router works here:
https://github.com/zeit/next.js/issues/2833#issuecomment-414919347

All 3 comments

I've also checked issues: #4545 #3322

I've solved the issue with a workaround, simply use query params without a custom server integration, just like below:

Workaround

Router.replace(`/path-to-route?param=${param}&param2=${param2}`, `/path-to-route/${param}/${param2}`, { shallow: true })

And then in the page wrap the component with withRouter

import { withRouter } from 'next/router';

class YourAwesomeComponent extends React.Component {
    render () {
        const { query } = this.props.router
        return <h1> {query.param} {query.param2} </h1>
    }
}

export default withRouter(YourAwesomeComponent)

Question

In my case the usage of a custom route on server.js was unuseful, but what if I need to do custom stuff in my custom route?

https://github.com/zeit/next.js/blob/canary/packages/next-server/lib/router/router.js#L208-L212

https://github.com/zeit/next.js/blob/canary/packages/next-server/lib/router/router.js#L370-L377

Shallow routing works by matching the href's path to a page inside the pages directory to the current page that's rendered. If they're the same page shallow will be used, if not we do a normal router.push/router.replace.

You can read more on how the router works here:
https://github.com/zeit/next.js/issues/2833#issuecomment-414919347

Was this page helpful?
0 / 5 - 0 ratings