0.0.6 • Published 3 years ago

@pastable/use-query-params v0.0.6

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

use-query-params

Hooks to handle query params state with react-router. Please check the tests folder if you need more detailed examples.

Usage

useQueryParams

Allows you to get/set page history with query params, usable like a useState. Is used by useQueryParamsState.

const [queryParams, setQueryParams] = useQueryParams();

UseQueryParamsProps

interface UseQueryParamsProps<QP = ObjectLiteral> {
    /** Getter used to parse query params as object from query string */
    getterFormater?: Formater<QP[keyof QP], any, keyof QP>;
    /** Setter used to serialize query string from query param object */
    setterFormater?: Formater<QP[keyof QP], any, keyof QP>;
    /**
     * Allow overriding the pathname on which the history will be pushed/replaced,
     * defaults to current history.location.pathname
     * Either pass a static toPath or a function that will be given basePath as argument
     */
    toPath?: string;
}

useQueryParamsState

Control a queryParam from its key like a useState. First prop is the query param key, second (optional) key is UseQueryParamsProps.

const [page, setPage] = useQueryParamsState("page");

useCurrentQueryParams

Get parsed query params, might be formated using given method. Is used by useQueryParams(#useQueryParams).

const queryParams = useCurrentQueryParams();

Only mandatory prop is getterFormater from UseQueryParamsProps, can be passed directly like this : const queryParams = useCurrentQueryParams(customFormater);

useSetQueryParams

Update page history by merging current queryParams with values. Is used by useQueryParams(#useQueryParams).

const setQueryParams = useSetQueryParams();

Accepts a prop object containing both toPath & formater (setterFormatter) from UseQueryParamsProps.

useQueryParamsMerger

Merge current queryParams with values and return the resulting query string. Is used by useSetQueryParams(#useSetQueryParams).

const merger = useQueryParamsMerger();

formatObjToQueryString

Remove object keys if not valid as query params. Is used by useQueryParamsMerger(#useQueryParamsMerger).

const queryString = formatObjToQueryString(params, customFormater);