Using with Next Router to listen to URL changes
ianyoung opened this issue · 0 comments
ianyoung commented
This is my first time using use-between
and I've hit a problem which is very similar to #43. I'm using Next.js and Next Router.
Basically I've created a custom hook which uses useEffect
and Next.js useRouter
to read the query params on first render and listen to changes afterwards:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const useQueryParams = () => {
const router = useRouter();
useEffect(() => {
const { market, beds, pricemin, pricemax, location, agent, sortby, page } = router.query;
// ...set state accordingly
}, [router.query]);
const updateUrl = ({ market, bedrooms, pricemin, pricemax, location, agent, sortby, page } = {}) => {
const { query } = router;
// ...modify query params accordingly
router.push({
pathname: router.pathname,
query: query,
});
};
return { updateUrl };
};
export const useSharedQueryParams = () => useBetween(useQueryParams);
I'm then trying to use this in a Next.js page like so:
import { useRouter } from 'next/router';
import { useBetween } from 'use-between';
import useSharedQueryParams from '@/hooks/useQueryParams';
const BuyPage = () => {
const { updateUrl } = useBetween(useSharedQueryParams);
// ...
}
But I'm receiving the error:
Error: Hook "useContext" no possible to using inside useBetween scope.
Can you provide any guidance on how to implement the fix suggested in #43 with Next Router?