|
1
|
import { useMemo } from "react" |
|
2
|
import { Path, useLocation } from "react-router-dom" |
|
3
|
|
|
4
|
/** |
|
5
|
* Checks if the current location has a restore_params property. |
|
6
|
* If it does, it will return a new path with the params added to it. |
|
7
|
* Otherwise, it will check if the current location has search params and preserve them. |
|
8
|
* Otherwise, it will return the previous path. |
|
9
|
* |
|
10
|
* This is useful if the modal needs to return to the original path, with |
|
11
|
* the params that were present when the modal was opened. |
|
12
|
*/ |
|
13
|
export const useStateAwareTo = (prev: string | Partial<Path> | number) => { |
|
14
|
const location = useLocation() |
|
15
|
|
|
16
|
const to = useMemo(() => { |
|
17
|
if (typeof prev === "number") { |
|
18
|
return prev |
|
19
|
} |
|
20
|
|
|
21
|
const params = location.state?.restore_params |
|
22
|
|
|
23
|
if (params) { |
|
24
|
return `${prev}?${params.toString()}` |
|
25
|
} |
|
26
|
|
|
27
|
// If no restore_params in state, check if the current URL has search params |
|
28
|
if (location.search) { |
|
29
|
return `${prev}${location.search}` |
|
30
|
} |
|
31
|
|
|
32
|
return prev |
|
33
|
}, [location.state, location.search, prev]) |
|
34
|
|
|
35
|
return to |
|
36
|
} |