Skip to content

Commit

Permalink
Make D2 the value return type so withDefault works #91
Browse files Browse the repository at this point in the history
  • Loading branch information
pbeshai committed Apr 21, 2020
1 parent fc51870 commit ce9e248
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
20 changes: 11 additions & 9 deletions examples/react-router/src/UseQueryParamExample.tsx
Expand Up @@ -4,11 +4,12 @@ import {
StringParam,
NumberParam,
ArrayParam,
withDefault,
} from 'use-query-params';

const MyParam = {
encode: (val: number) => `MY_${val}`,
decode: (input: string | (string| null)[] | null | undefined) => {
decode: (input: string | (string | null)[] | null | undefined) => {
const str = input instanceof Array ? input[0] : input;
return str == null ? undefined : +str.split('_')[1];
},
Expand All @@ -20,7 +21,10 @@ const UseQueryParamExample = () => {
const [custom, setCustom] = useQueryParam('custom', MyParam);
const [test, setTest] = useQueryParam('test', StringParam);
const [anyp, setAnyP] = useQueryParam('anyp');
const [arr, setArr] = useQueryParam('arr', ArrayParam);
const [arr, setArr] = useQueryParam(
'arr',
withDefault(ArrayParam, [] as (string | null)[])
);

// verify we aren't creating new arrays each time
const prevArr = React.useRef(arr);
Expand Down Expand Up @@ -106,13 +110,11 @@ const UseQueryParamExample = () => {
<tr>
<td>arr</td>
<td>
{arr
? arr.map((d: string | null, i: number) => (
<div key={i}>
arr[{i}] = {d}
</div>
))
: arr}
{arr.map((d: any, i: number) => (
<div key={i}>
arr[{i}] = {d}
</div>
))}
</td>
<td>{typeof arr}</td>
<td>
Expand Down
5 changes: 1 addition & 4 deletions src/useQueryParam.ts
Expand Up @@ -81,10 +81,7 @@ function getLatestDecodedValue<D, D2 = D>(
export const useQueryParam = <D, D2 = D>(
name: string,
paramConfig: QueryParamConfig<D, D2> = StringParam as QueryParamConfig<any>
): [
D2 | undefined,
(newValue: NewValueType<D>, updateType?: UrlUpdateType) => void
] => {
): [D2, (newValue: NewValueType<D>, updateType?: UrlUpdateType) => void] => {
const { location, getLocation, setLocation } = useLocationContext();

// read in the raw query
Expand Down

0 comments on commit ce9e248

Please sign in to comment.