-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (41 loc) · 1.45 KB
/
index.js
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
import React, { useContext, useCallback, useEffect, useState } from 'react';
const PathnameContext = React.createContext(null);
const UpdateContext = React.createContext(() => {});
const getPathname = () => `${window.location.pathname}`;
const BrowserPathname = ({children}) => {
const [location, setLocation] = useState(getPathname());
const setCurrentBrowserPathname = useCallback(() => {
setLocation(getPathname());
}, []);
useEffect(() => {
window.addEventListener('popstate', setCurrentBrowserPathname);
return () => {
window.removeEventListener('popstate', setCurrentBrowserPathname);
};
}, [setCurrentBrowserPathname]);
return React.createElement(
UpdateContext.Provider,
{ value: setCurrentBrowserPathname },
React.createElement(
PathnameContext.Provider,
{ value: location },
children
)
);
};
export const useBrowserPathname = () => useContext(PathnameContext);
export const usePushPath = () => {
const setCurrentBrowserPathname = useContext(UpdateContext);
return useCallback(path => {
window.history.pushState({}, null, path);
setCurrentBrowserPathname();
},[setCurrentBrowserPathname]);
};
export const useReplacePath = () => {
const setCurrentBrowserPathname = useContext(UpdateContext);
return useCallback(path => {
window.history.replaceState({}, null, path);
setCurrentBrowserPathname();
},[setCurrentBrowserPathname]);
};
export default BrowserPathname;