router.js
40 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | import { |
| 5 | createContext, |
| 6 | useContext, |
| 7 | useSyncExternalStore, |
| 8 | } from '@wordpress/element'; |
| 9 | |
| 10 | /** |
| 11 | * Internal dependencies |
| 12 | */ |
| 13 | import history from './history'; |
| 14 | |
| 15 | const RoutesContext = createContext(); |
| 16 | const HistoryContext = createContext(); |
| 17 | |
| 18 | export function useLocation() { |
| 19 | return useContext( RoutesContext ); |
| 20 | } |
| 21 | |
| 22 | export function useHistory() { |
| 23 | return useContext( HistoryContext ); |
| 24 | } |
| 25 | |
| 26 | export function RouterProvider( { children } ) { |
| 27 | const location = useSyncExternalStore( |
| 28 | history.listen, |
| 29 | history.getLocationWithParams, |
| 30 | history.getLocationWithParams |
| 31 | ); |
| 32 | |
| 33 | return ( |
| 34 | <HistoryContext.Provider value={ history }> |
| 35 | <RoutesContext.Provider value={ location }> |
| 36 | { children } |
| 37 | </RoutesContext.Provider> |
| 38 | </HistoryContext.Provider> |
| 39 | ); |
| 40 | } |