HMR
HMR

Reputation: 39320

next js Router.push reloads page

When I do Router.push my page reloads, I would expect pushState to be used.

Using the following code in the component:

import Router from "next/router";
//other code
const search = useCallback(
  e => {
    e.preventDefault();
    Router.push(
      `/products-search/${encodeURIComponent(
        searchText
      )}`,
      `/products-search?q=${encodeURIComponent(
        searchText
      )}`
    );
  },
  [searchText]
);
//other code
<form onSubmit={search}>
  <input
    type="text"
    onChange={change}
    value={searchText}
    pattern=".{3,}"
    title="3 characters minimum"
    required
  />
  <button type="submit">OK</button>
</form>

My page/products-search.js

ProductsSearch.getInitialProps = ({ query, store }) => {
  //added try catch as next js may reload if there is an error
  //  running this on the client side
  try {
    const queryWithPage = withPage(query);
    return {
      query: queryWithPage
    };
  } catch (e) {
    debugger;
  }
};

Upvotes: 7

Views: 13930

Answers (3)

Zen-Ventzi-Marinov
Zen-Ventzi-Marinov

Reputation: 4236

In case some lost soul comes here with my issue, it was kind of invisible.

router.push(
      '/organizations/[oid]/clients/[uid]',
      `/organizations/${oid}/clients/${id}`
    );

is what I wrote and it navigated without a refresh.

router.push(
      '/organizations/[oid]/clients/[cid]',// cid mistaken name but still worked. Should be uid
      `/organizations/${oid}/clients/${id}`
    );

The mistaken id name was causing the refresh, though it still navigated to the right page. So, make sure the id names are correct.

Upvotes: 14

Vish
Vish

Reputation: 1

const search = () => { router.push( /products-search/[searchText], /products- search/${searchText}, {shallow: true} );

}

Upvotes: -1

HMR
HMR

Reputation: 39320

When I pass an object to Router.push it works as expected:

const search = useCallback(
  e => {
    e.preventDefault();
    Router.push({
      pathname: "/products-search",
      query: { q: searchText }
    });
  },
  [searchText]
);

Upvotes: 6

Related Questions