Ripas55
Ripas55

Reputation: 953

How do I sync my search state with Url and connect it to next.js router?

I am following the react instant search example here - https://www.algolia.com/doc/guides/building-search-ui/going-further/routing-urls/react/

const createURL = state => `?${qs.stringify(state)}`;

const searchStateToUrl = searchState =>
  searchState ? createURL(searchState) : '';

const urlToSearchState = ({ search }) => qs.parse(search.slice(1));

An I'm having difficulty understanding how this would work in next js, because how can I connect the searchStateToUrl function to my next router, since I am not accepting any props in next js?

export function App({ location, history }) {
  const [searchState, setSearchState] = useState(urlToSearchState(location));
  const debouncedSetStateRef = useRef(null);

  function onSearchStateChange(updatedSearchState) {
    clearTimeout(debouncedSetStateRef.current);

    debouncedSetStateRef.current = setTimeout(() => {
      history.push(searchStateToUrl(location, updatedSearchState));
    }, DEBOUNCE_TIME);

    setSearchState(updatedSearchState);
  }

  useEffect(() => {
    setSearchState(urlToSearchState(location));
  }, [location]);

Upvotes: 0

Views: 1360

Answers (1)

Did you saw this example from Vercel?

https://github.com/vercel/next.js/blob/canary/examples/with-algolia-react-instantsearch/pages/index.js

This example is done with classes, but the only thing you have to change is tho way to capture the path because with next you are not using react-router.

Just change the function searchStateToUrl and the useEffect in the Algolia docs example to the following and should work.

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

and

  useEffect(() => {
    setSearchState(urlToSearchState({ search: window.location.search.slice(1) }));
  }, [location]);

Upvotes: 0

Related Questions