npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-query-filters-manager

v1.1.2

Published

react-query-filters-manager

Downloads

38

Readme

react-query-filters-manager NPM Module

A library for management your data in project.

The storing and updating data depend on @tanstack/react-query.

Requirements

This package has the following peer dependencies:

Install

npm i react-query-filters-manager

Principle of working

  1. Data is collected using useQuery + getFiltersValues. Filters are taken from the request parameters, or, if they have not yet been applied to the page, from initialFilters.
  2. To update the filter, use setFilters, that call handleSetFiltersInUrl. It updates the data using setFiltersValues , then queryClient.invalidateQueries happens by the key filterKey, and writing a new history in the URL.
  3. To save filters in the URL as query parameters. Using queryString.stringify the object is converted to a string request parameters. Next, the incoming URL is added using the router.replace method.
  4. To reset the recovery data, handleChange, which repeats 2 step with the initial data.
  5. When filters are changed, the method for obtaining data is called.

Usage

Here is a very basic example of how to use Next Router Guards.

  1. Wrap your project into FiltersManagerContextProvider in _app.tsx.
  2. Create you hook that return UseFiltersState.
  3. Call useFilters and pass generic parameters:
    • TData - type of the management data (required);
    • TFilters - type of filters that affect on your data (required);
    • TFiltersPrepared - type of data that will be caching in url of page;
    • TVariants - type of variants your filter's data.
  4. Pass needed params to useFilters.

Example:

// /pages/_app.tsx

import {FiltersManagerContextProvider} from 'react-query-filters-manager';

function MyApp({pageProps}: AppProps) {
  const queryClient = useMemo<QueryClient>(() => new QueryClient(), []);
  const router = useRouter()
  
  return (
    <>
      <Head>
         ...
      </Head>

      <QueryClientProvider client={queryClient}>
        <FiltersManagerContextProvider queryClient={queryClient} router={router}>
          ...
        </FiltersManagerContextProvider>
      </QueryClientProvider>
    </>
  );
}

export default MyApp;
// cart_filters.service.ts

import {useFilters, type UseFiltersState} from 'react-query-filters-manager';

export const useCartFilters = (): UseFiltersState<CartModel, CartFiltersModel> => {
  const initialFilters = useMemo<CartFiltersModel>(
    () => ({
      page: 1,
      perPage: DEFAULT_PAGINATION_STEP,
      sortBy: null,
      sortDirection: 'asc',
    }),
    [],
  );

  const queryParser = useCallback(
    (queries: ParsedQuery): CartFiltersModel => ({
      page: parseNumberHelper(queries.page, 1),
      perPage: parseNumberHelper(queries.perPage, 50),
      sortBy: parseStringHelper(queries.sortBy, null) as CartFiltersModel['sortBy'],
      sortDirection: parseStringHelper(queries.sortDirection, 'asc') as SortDirectionModel,
    }),
    [],
  );

  const getCartFiltersValues = useCallback(async () => getFiltersValuesLocal<CartFiltersModel>(cartKey), []);
  const setCartFiltersValues = useCallback(
    async (data: CartFiltersModel) => setFiltersValuesLocal<CartFiltersModel>({filtersKey: cartKey, filters: data}),
    [],
  );

  return useFilters<CartModel, CartFiltersModel>({
    filtersKey: [cartKey],
    getData: getCartByFiltersApi,
    initialFilters,
    queryParser,
    getFiltersValues: getCartFiltersValues,
    setFiltersValues: setCartFiltersValues,
  });
};

State

The useFilters return methods and parameters:

export type UseFiltersState<TData, TFilters, TVariants = void> = {
  // Count of applied filters.
  appliedFiltersCount: number;

  // Initial state of filters.
  initialFilters: TFilters;

  // The current state of the filters.
  filters: UseQueryResult<TFilters, ErrorModel>;

  // Data received from a filter.
  values: UseQueryResult<TData, ErrorModel>;

  // Filter value options.
  variants: UseQueryResult<TVariants | null, ErrorModel>;

  // Filter update.
  setFilters: UseMutationResult<TFilters, any, TFilters>;

  // Reset filters with the ability to change the field.
  resetFilters: UseMutationResult<TFilters, any, void | ResetFilterCallback<TFilters>>;
};

Parameters

For use useFilters you need to pass parameters:

type Props<TData, TFilters, TFiltersPrepared = TFilters, TVariants = void> = {
  // The key by which the data will be updated.
  filtersKey: QueryKey;

  // Initial state of filters.
  initialFilters: TFilters;

  // Getting data by filters.
  getData: (params: TFilters) => Promise<TData>;

  // Convert query params to filter object.
  queryParser: (query: ParsedQuery) => TFilters;

  // Getting filters.
  getFiltersValues: () => Promise<TFilters | undefined>;

  // Update filters.
  setFiltersValues: (data: TFilters) => Promise<TFilters>;

  // Preparing data for entering it into query params.
  queryTransformer?: (data: TFilters) => TFiltersPrepared;

  // Getting count of applied filters.
  getAppliedFiltersCount?: (params: TFilters) => number;

  // Getting filter options.
  getVariants?: () => Promise<TVariants>;

  // Options for retrieving data.
  valuesOptions?: Omit<UseQueryOptions<TData, ErrorModel, TData>, 'queryKey' | 'queryFn' | 'initialData'> & {
    initialData?: () => undefined;
  };
};

License

react-query-filters-manager is released under the MIT license.