Skip to content

Commit

Permalink
Do not fail when localstorage isn't available
Browse files Browse the repository at this point in the history
  • Loading branch information
thgreasi authored Oct 24, 2017
1 parent 5539673 commit f03fc2d
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,49 @@ function rejectWithMessage(error) {
return Promise.reject(error.message);
}

const store = (() => {
function isLocalStorageValid() {
try {
return typeof localStorage !== 'undefined' &&
('setItem' in localStorage) &&
typeof localStorage.setItem === 'function';
} catch (e) {
return false;
}
}

if (isLocalStorageValid()) {
return localStorage;
}

return {
db: {},
setItem(key, value) {
this.db[key] = value;
},
getItem(key, value) {
const value = this.db[key];
if (value === undefined) {
// emulate localStorage
return null;
}
return value
}
};
})();

export default (key, replacer, reviver) => ({
load() {
return new Promise((resolve) => {
const jsonState = localStorage.getItem(key);
const jsonState = store.getItem(key);
resolve(JSON.parse(jsonState, reviver) || {});
}).catch(rejectWithMessage);
},

save(state) {
return new Promise((resolve) => {
const jsonState = JSON.stringify(state, replacer);
localStorage.setItem(key, jsonState);
store.setItem(key, jsonState);
resolve();
}).catch(rejectWithMessage);
}
Expand Down

0 comments on commit f03fc2d

Please sign in to comment.