-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (73 loc) · 1.92 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Keys that we use for storing user's data in localStorage
let KEYS = {
token: "AUTH_TOKEN",
user: "USER",
};
// Incase if you want to keep different name for user's data then use this function to do that first
const updateConfig = (config) => {
KEYS = {
...config,
};
};
// wrapping up methods of localStorage with checking of it's existence (useful when you're using SSR)
const LocalStorage = {
get: (key) => {
if (typeof localStorage !== "undefined") {
return localStorage.getItem(key);
}
return false;
},
getJSON: (key) => {
if (typeof localStorage !== "undefined") {
const data = LocalStorage.get(key);
return data && data !== "undefined" ? JSON.parse(data) : "";
}
return false;
},
set: (...rest) => {
if (typeof localStorage !== "undefined") {
return localStorage.setItem(...rest);
}
return false;
},
setJSON: (key, value) => {
if (typeof localStorage !== "undefined") {
const data = JSON.stringify(value);
return LocalStorage.set(key, data);
}
return false;
},
remove: (key) => {
if (typeof localStorage !== "undefined") {
return localStorage.removeItem(key);
}
return false;
},
clean: () => {
if (typeof localStorage !== "undefined") {
return localStorage.clear();
}
return false;
},
};
// # functions to manipulate user's data
const setToken = (token) => {
LocalStorage.set(KEYS.token, token);
};
const setUser = (user) => {
LocalStorage.set(KEYS.user, JSON.stringify(user));
};
const getToken = () => {
if (typeof localStorage !== "undefined") {
return LocalStorage.get(KEYS.authToken) || "";
}
return "";
};
const getUser = async () => {
if (typeof localStorage !== "undefined") {
const user = LocalStorage.get(KEYS.user);
return user && JSON.parse(user);
}
return {};
};
export { LocalStorage, getUser, getToken, setUser, setToken, updateConfig };