-
Notifications
You must be signed in to change notification settings - Fork 0
/
useURLState.ts
65 lines (49 loc) · 1.64 KB
/
useURLState.ts
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useEffect } from 'react';
import { subscribeKey } from 'valtio/utils';
import store from '../state';
import { useHistory, useParams } from 'react-router-dom'
import { useDebouncedValue } from '../utils/useDebouncedValue';
export const useURLState = () => {
useUserDetailURLState();
useUserSearchURLState();
}
export type UserDetailParams = {
username: string
}
export const useUserDetailURLState = () => {
const params = useParams<Partial<UserDetailParams>>();
const [debouncedUsername] = useDebouncedValue(params.username, 200);
useEffect(() => {
// console.log("Set Store Username", debouncedUsername)
store.username = debouncedUsername;
}, [debouncedUsername]);
}
export type UserSearchParams = {
query: string,
page: string
}
export const useUserSearchURLState = () => {
const history = useHistory();
const params = useParams<Partial<UserSearchParams>>();
const [debouncedFilter] = useDebouncedValue(params.query, 200);
const [debouncedPage] = useDebouncedValue(params.page, 200);
useEffect(() => {
store.page = parseInt(debouncedPage || '1');
}, [debouncedPage]);
useEffect(() => {
store.userFilter = debouncedFilter || '';
}, [debouncedFilter]);
const refreshURL = () => {
if(store.userFilter.length < 1) {
history.push(`/`);
return;
}
history.push(`/search/${store.userFilter}/${store.page}`);
};
useEffect(() => subscribeKey(store, 'userFilter', () => {
refreshURL();
}), []);
useEffect(() => subscribeKey(store, 'page', () => {
refreshURL();
}), []);
}