Skip to content

Commit 4882b4e

Browse files
committed
[FIX] localStorage is not exist
1 parent c75c99b commit 4882b4e

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/store/user.js

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@ import faker from 'faker';
22
const DB_KEY = 'REACT_USERS';
33
let data = [];
44

5+
function hasSupportLocalStorage() {
6+
var mod = 'modernizr';
7+
try {
8+
localStorage.setItem(mod, mod);
9+
localStorage.removeItem(mod);
10+
return true;
11+
} catch (e) {
12+
return false;
13+
}
14+
}
15+
516
function getRandomIntInclusive(min, max) {
617
min = Math.ceil(min);
718
max = Math.floor(max);
@@ -23,14 +34,16 @@ function initFakeData() {
2334
nickname: faker.internet.userName()
2435
});
2536
}
26-
localStorage.setItem(DB_KEY, JSON.stringify(data));
37+
hasSupportLocalStorage() &&
38+
localStorage.setItem(DB_KEY, JSON.stringify(data));
2739
}
2840
}
2941

3042
function addUser(user, callback) {
3143
const newUser = { id: faker.random.uuid(), ...user };
3244
data.push(newUser);
33-
localStorage.setItem(DB_KEY, JSON.stringify(data));
45+
hasSupportLocalStorage() &&
46+
localStorage.setItem(DB_KEY, JSON.stringify(data));
3447
callback && callback();
3548
}
3649

@@ -40,7 +53,8 @@ function removeUser(userId, callback) {
4053
if (foundIndex !== -1) {
4154
data.splice(foundIndex, 1);
4255
}
43-
localStorage.setItem(DB_KEY, JSON.stringify(data));
56+
hasSupportLocalStorage() &&
57+
localStorage.setItem(DB_KEY, JSON.stringify(data));
4458
callback && callback();
4559
}
4660

@@ -50,7 +64,8 @@ function updateUser(userId, user, callback) {
5064
const updateData = Object.assign({}, data[foundIndex], user);
5165
data.splice(foundIndex, 1, updateData);
5266
}
53-
localStorage.setItem(DB_KEY, JSON.stringify(data));
67+
hasSupportLocalStorage() &&
68+
localStorage.setItem(DB_KEY, JSON.stringify(data));
5469
callback && callback();
5570
}
5671

0 commit comments

Comments
 (0)