fenok / react-router-typesafe-routes

Comprehensive and extensible type-safe routes for React Router v6 with first-class support for nested routes and param validation.
MIT License
151 stars 3 forks source link

Is it possible to have an array search param with multiple defaults #47

Closed mikedidthis closed 8 months ago

mikedidthis commented 8 months ago

👋

Firstly thank you for the amazing library! I am trying to replicate the ArrayParam behaviour from use-query-params.

?qp=one&qp=two

If qp is missing I want to set the default values to ['one', 'two']. However it looks like default() only expects a string (unless I am missing something?).

fenok commented 8 months ago

Hello and thank you!

array() is a terminating modifier that ensures the parsed value will be an array (and default() only affects the items of this array). As of now, there is no way to specify a default value in this case (in a way, it's implicitly set to []).

You can build a custom type to get the behavior you want:

const stringArray = (def: string[]): SearchParamType<string[]> => ({
    getPlainSearchParam(value) {
        // No need to check for undefined, and values are escaped automatically
        return value;
    },
    getTypedSearchParam(value) {
        // Values are automatically unescaped, and empty array means that there is no such param
        return value.length ? value : def;
    },
});

const MyRoute = route("", { searchParams: { qp: stringArray(["one", "two"]) } });

I hope this helps.

mikedidthis commented 8 months ago

Perfect! Works as expected thanks for the quick response.