-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
43 lines (38 loc) · 1.04 KB
/
index.ts
File metadata and controls
43 lines (38 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import {Dispatch, SetStateAction, useEffect, useRef, useState} from 'react';
import {
ParseOptions,
ParsedQuery,
StringifyOptions,
parse,
stringify
} from 'query-string';
export interface QueryStringResult {
[0]: ParsedQuery;
[1]: Dispatch<SetStateAction<Record<string, any>>>;
}
export default function useQueryString(
location: Location,
navigate: (path: string) => void,
parseOptions?: ParseOptions,
stringifyOptions?: StringifyOptions
): QueryStringResult {
const isFirst = useRef(true);
const [state, setState] = useState(parse(location.search, parseOptions));
useEffect((): void => {
if (isFirst.current) {
isFirst.current = false;
} else {
navigate(location.pathname + '?' + stringify(state, stringifyOptions));
}
}, [state]);
const setQuery: typeof setState = (values): void => {
const nextState = typeof values === 'function' ? values(state) : values;
setState(
(state): ParsedQuery => ({
...state,
...nextState
})
);
};
return [state, setQuery];
}