Skip to content

Commit

Permalink
Remove side-effect in StorageAPI that overrides localStorage.clear (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMightyPenguin authored Dec 1, 2022
1 parent 10e97bb commit 695100b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/gold-cups-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphiql/toolkit': patch
---

Remove side-effect in StorageAPI that overrides localStorage.clear
6 changes: 5 additions & 1 deletion packages/graphiql-toolkit/src/storage/__tests__/base.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { StorageAPI } from '../base';

describe('StorageAPI', () => {
const storage = new StorageAPI();
let storage = new StorageAPI();

beforeEach(() => {
storage = new StorageAPI();
});

it('returns nothing if no value set', () => {
const result = storage.get('key1');
Expand Down
29 changes: 22 additions & 7 deletions packages/graphiql-toolkit/src/storage/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,29 @@ export class StorageAPI {
// Passing `null` creates a noop storage
this.storage = null;
} else if (typeof window !== 'undefined') {
this.storage = window.localStorage;
// We only want to clear the namespaced items
this.storage.clear = () => {
for (const key in window.localStorage) {
if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) {
window.localStorage.removeItem(key);
this.storage = {
getItem: window.localStorage.getItem.bind(window.localStorage),
setItem: window.localStorage.setItem.bind(window.localStorage),
removeItem: window.localStorage.removeItem.bind(window.localStorage),

get length() {
let keys = 0;
for (const key in window.localStorage) {
if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) {
keys += 1;
}
}
}
return keys;
},

clear: () => {
// We only want to clear the namespaced items
for (const key in window.localStorage) {
if (key.indexOf(`${STORAGE_NAMESPACE}:`) === 0) {
window.localStorage.removeItem(key);
}
}
},
};
} else {
this.storage = null;
Expand Down

0 comments on commit 695100b

Please sign in to comment.