Skip to content

Commit 3ab42bc

Browse files
authored
Merge pull request #32 from AdrianaCAA/master
Resolves JavaScript error when parsing corrupt localstorage data
2 parents 88f1495 + 317de7d commit 3ab42bc

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/index.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ function lsKey(env, user) {
209209
}
210210

211211
function initialize(env, user, options) {
212+
var localStorageKey;
212213
options = options || {};
213214
environment = env;
214215
flags = typeof(options.bootstrap) === 'object' ? options.bootstrap : {};
@@ -221,20 +222,26 @@ function initialize(env, user, options) {
221222
emitter = EventEmitter();
222223
ident = Identity(user, sendIdentifyEvent);
223224
requestor = Requestor(baseUrl, environment);
224-
225+
localStorageKey = lsKey(environment, ident.getUser());
226+
225227
if (typeof options.bootstrap === 'object') {
226228
// Emitting the event here will happen before the consumer
227229
// can register a listener, so defer to next tick.
228230
setTimeout(function() { emitter.emit(readyEvent); }, 0);
229231
}
230232
else if (typeof(options.bootstrap) === 'string' && options.bootstrap.toUpperCase() === 'LOCALSTORAGE' && typeof(Storage) !== 'undefined') {
231233
useLocalStorage = true;
232-
flags = JSON.parse(localStorage.getItem(lsKey(environment, ident.getUser())));
234+
// check if localstorage data is corrupted, if so clear it
235+
try {
236+
flags = JSON.parse(localStorage.getItem(localStorageKey));
237+
} catch (error) {
238+
localStorage.setItem(localStorageKey, null);
239+
}
233240

234241
if (flags === null) {
235242
requestor.fetchFlagSettings(ident.getUser(), hash, function(err, settings) {
236243
flags = settings;
237-
localStorage.setItem(lsKey(environment, ident.getUser()), JSON.stringify(flags));
244+
localStorage.setItem(localStorageKey, JSON.stringify(flags));
238245
emitter.emit(readyEvent);
239246
});
240247
} else {
@@ -243,7 +250,7 @@ function initialize(env, user, options) {
243250
// the in-memory flags unless you subscribe for changes
244251
setTimeout(function() { emitter.emit(readyEvent); }, 0);
245252
requestor.fetchFlagSettings(ident.getUser(), hash, function(err, settings) {
246-
localStorage.setItem(lsKey(environment, ident.getUser()), JSON.stringify(settings));
253+
localStorage.setItem(localStorageKey, JSON.stringify(settings));
247254
});
248255
}
249256
}

0 commit comments

Comments
 (0)