search-ui icon indicating copy to clipboard operation
search-ui copied to clipboard

Nextjs Integration guide is not working with Nextjs 14 with app directory

Open Tamimjabr opened this issue 2 years ago • 2 comments

The following approach is not working with Nextjs 14 using app directory

   import { memo } from 'react'
   import { useNextRouting } from "../utils/useNextRouting";

   export default function App() {
     // useNextRouting is a custom hook that will integrate with Next Router with Search UI config
     // config is search-ui configuration.
     // baseUrl is the path to the search page
     const combinedConfig = useNextRouting(config, "<baseUrl>");
     return <Search config={combinedConfig} />;
   }

   const Search = memo(({ config }) => {
     return (
       <SearchProvider config={config}>
         <>
           <ResultsPerPage />
           <Results config={config} />
           <Paging />
         </>
       </SearchProvider>
       )
   })

   ```

```jsx
import { useRouter } from "next/router";
import { useMemo } from "react";

export const useNextRouting = (config, basePathUrl) => {
 const router = useRouter();
 const { asPath } = router;

 const getSearchParamsFromUrl = (url) => {
   return url.match(/\?(.+)/)?.[1] || "";
 };

 const routingOptions = {
   // read and write only the query string to search UI
   // as we are leveraging existing stateToUrl and urlToState functions
   // which are based on the query string
   readUrl: () => {
     return getSearchParamsFromUrl(asPath);
   },
   writeUrl: (url, { replaceUrl }) => {
     const method = router[replaceUrl ? "replace" : "push"];
     const params = Object.fromEntries(new URLSearchParams(url).entries());
     method({ query: { ...router.query, ...params } }, undefined, {
       shallow: true
     });
   },
   routeChangeHandler: (callback) => {
     const handler = (fullUrl) => {
       if (fullUrl.includes(basePathUrl)) {
         callback(getSearchParamsFromUrl(fullUrl));
       }
     };
     router.events.on("routeChangeComplete", handler);
     return () => {
       router.events.off("routeChangeComplete", handler);
     };
   }
 };

 return useMemo(() => {
   return {
     ...config,
     routingOptions
   };
 }, [router.isReady]);
};

Tamimjabr avatar Dec 16 '23 10:12 Tamimjabr

thanks for reporting the issue. Will look into it.

joemcelroy avatar Jan 26 '24 10:01 joemcelroy

It still not work with Nextjs App Router 😭

fireswork avatar Apr 11 '24 05:04 fireswork

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Is this issue still important to you? If so, please leave a comment and let us know. As always, thank you for your contributions.

botelastic[bot] avatar Jun 10 '24 06:06 botelastic[bot]