Skip to content

Using with Next Router to listen to URL changes #44

@ianyoung

Description

@ianyoung

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions