Changing Query paramers while staying on the same page without reload= NextJS Router

Viewed 434

for a project I am working on I am running into a problem with the nextjs Router.I have a component that has an input field which the user should be able to input their searchterm in. There is a different component which should be able to get this searchterm and perform a search.

Because the two components aren't connected I would like to set the queryParameters in the router in the Input component, and then execute a function in the search component when the searchTerm is changed.

The problem lies in the following: The searchComponent receives the nextJS router as props and will only execute my useEffect function when those props are changed (and react knows they are changed), on top of that I need to stay on the same page when updating the query parameters, but the route of this page is dynamic. For example: the user can add this combination of components on /search but also on /lookforitem.

I have tried setting the queryParameters in the following way in the Input component:

  function setQueryParams() {
    router.query = {
      ...router.query,
      searchTerm: input.current,
    };
  }

In combination with the following code in the Search component:

useEffect(() => {
  console.log('Router has changed');
}, [router]);

The problem is that this useEffect doesnt get called untill the search component is rendered again (I have created a button that logs the router to the console, and it shows the updated router), which I assume is because React hasn't realised that the Router props have changed.

I have also tried setting the query parameters via a router.push in the following way:

function setQueryParams() {
  router.push(
    {
      pathname: router.route,
      query: {
        ...router.query,
        searchTerm: input.current,
      },
    },
    undefined,
    { shallow: true }
  );
}

However this comes with its own set of problems. First of all it causes a refresh of the page, which I don't want. On top of that it changes the url to for example: /search?searchTerm=Hello which means that if I enter a different input and submit it will stack making the next url for example: &searchterm=hello?searchterm=goodbye.

I want a way to update the query parameters without refreshing the page, but while also notifying the other components that use the router that the query parameters have updated. All of the searching that I've done seems to be specific to either routing to a different page or routing to a predefined page.

Any help would be greatly appreciated.

0 Answers
Related