Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: navigate() fine-grain URL options #2240

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

Conversation

brillout
Copy link
Member

@brillout brillout commented Mar 1, 2025

  import { navigate } from 'vike/client/router';
  import { useCallback } from 'react';
  import { usePageContext } from 'vike-react/usePageContext';

  export const useSearchParams = (): [
    URLSearchParams,
    (params: string[][] | Record<string, string> | string | URLSearchParams) => void,
  ] => {
    const pageContext = usePageContext();
    const { searchParams } = pageContext.urlParsed
    const setSearchParams = useCallback(
      (
        params: string[][] | Record<string, string> | string | URLSearchParams,
        options?: NavigateOptions,
      ) => {
        navigate({ search: new URLSearchParams(params), ...options})
      },
      [],
    );
    return [searchParams, setSearchParams];
  };

This is my favorite so far:

// URL current: /products?filter=cars#reviews
// URL next: /products#reviews
navigate('?')
// URL current: /products?filter=cars#reviews
// URL next: /products?filter=cars
navigate('#')
// URL current: /products?filter=cars#reviews
// URL next: /products
navigate('?#')
// URL current: /products?filter=cars&country=germany#reviews
// URL next: /products?filter=cars&sort=price#reviews
navigate({
  search: {
    // Add query
    sort: 'price',
    // Remove query
    country: null
  }
})
// URL current: /products?filter=cars&country=germany
// URL next: /products?filter=computers
navigate('?', {
  search: {
    // Add query
    filter: 'computers'
  }
})

Let me know if this covers your use cases and whether useSearchParams() has a feature not covered by this, and I'll implement it.

@brillout brillout mentioned this pull request Mar 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant