Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
};
like image 778
HMR Avatar asked Jan 14 '20 13:01

HMR


1 Answers

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.

like image 198
ZenVentzi Avatar answered Sep 23 '22 13:09

ZenVentzi