-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.js
71 lines (64 loc) · 1.93 KB
/
helpers.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { useState } from "react";
export function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}
export function toKebab(string) {
return string
.split("")
.map((letter, index) => {
if (/[A-Z]/.test(letter)) {
return ` ${letter.toLowerCase()}`;
}
return letter;
})
.join("")
.trim()
.replace(/[_\s]+/g, "-");
}
export const isSSR = typeof window !== "undefined";
export function useSessionStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
if (!isSSR) return initialValue;
try {
// Get from local storage by key
const item = window.sessionStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to sessionStorage.
const setValue = (value) => {
if (!isSSR) return "";
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.sessionStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
// export function useEmailCloaker(initialValue) {
// const email = addrs.parseOneAddress(initialValue);
// return [
// email?.local.charAt(0),
// email?.local.charAt(email?.local.length - 1),
// `@${email?.domain}`,
// ];
// }