'next.js router changes url, but still renders the same page. and doesn't navigate to another page

I have a route /discovery where I display my search results, I am also trying to sync my search state with url query params, so if user types "chicken" the url becomes - /discovery?query=chicken&page=1

once user clicks on the result it will navigate to /mealpreview/[id]

However when I am trying to navigate back like this:

      <IconButton color="inherit" onClick={() => router.back()}>
        <ArrowBackIcon />
      </IconButton>

the url changes back to - /discovery?query=chicken&page=1 but it still renders the same page.

When I click back button again it works and goes back to /discovery

When I don't use url params everything works, what is happening here?

By the way this is how I sync my url state:

import React, { Component } from "react";
import qs from "qs";

const updateAfter = 700;
export const isClient = !(typeof window === "undefined");

const searchStateToURL = (searchState) =>
  searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";

const withURLSync = (TestSearch) =>
  class WithURLSync extends Component {
    state = {
      searchState: qs.parse(isClient && window.location.search.slice(1)),
    };

    componentDidMount() {
      if (isClient) {
        window.addEventListener("popstate", this.onPopState);
      }
    }

    componentWillUnmount() {
      clearTimeout(this.debouncedSetState);
      window.removeEventListener("popstate", this.onPopState);
    }

    onPopState = ({ state }) =>
      this.setState({
        searchState: state || {},
      });

    onSearchStateChange = (searchState) => {
      clearTimeout(this.debouncedSetState);

      this.debouncedSetState = setTimeout(() => {
        window.history.pushState(
          searchState,
          null,
          searchStateToURL(searchState)
        );
      }, updateAfter);

      this.setState({ searchState });
    };

    render() {
      const { searchState } = this.state;

      return (
        <TestSearch
          {...this.props}
          searchState={searchState}
          onSearchStateChange={this.onSearchStateChange}
          createURL={searchStateToURL}
        />
      );
    }
  };

export default withURLSync;



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source