From 3bc3729f4501989b54e552346c95ef28954d7d59 Mon Sep 17 00:00:00 2001 From: Anton Gilgur Date: Mon, 18 Nov 2019 22:52:10 -0500 Subject: [PATCH] (fix): resolve AsyncLocalStorage Illegal Invocation errors - I (and apparently most mst-persist users) don't use localStorage, so this bug went undetected for a while until someone reported a bug - and I finally hit upon it myself when adding tests shortly after, which added a solid reproduction as well as a blocker on it - it made localStorage unusable as all of AsyncLocalStorage's calls would give Illegal Invocation errors - see https://stackoverflow.com/q/41126149/3431180 for more details - using .call did not work, not on callWithPromise.call(window, ...) nor func.call(window, ...args) - similarly window.localStorage.func.bind(window) did not work - so instead used wrapper functions as an alternative that didn't feel too convoluted - using window.localStorage[funcKey] in callWithPromise did not quite feel right, wrapper functions felt better --- src/asyncLocalStorage.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/asyncLocalStorage.ts b/src/asyncLocalStorage.ts index 4a91d52..16856d5 100644 --- a/src/asyncLocalStorage.ts +++ b/src/asyncLocalStorage.ts @@ -6,17 +6,18 @@ interface IAsyncLocalStorage { } export const AsyncLocalStorage: IAsyncLocalStorage = { + // must use wrapper functions when passing localStorage functions (https://github.com/agilgur5/mst-persist/issues/18) clear () { - return callWithPromise(window.localStorage.clear) + return callWithPromise(() => window.localStorage.clear()) }, getItem (key) { - return callWithPromise(window.localStorage.getItem, key) + return callWithPromise(() => window.localStorage.getItem(key)) }, removeItem (key) { - return callWithPromise(window.localStorage.removeItem, key) + return callWithPromise(() => window.localStorage.removeItem(key)) }, setItem (key, value) { - return callWithPromise(window.localStorage.setItem, key, value) + return callWithPromise(() => window.localStorage.setItem(key, value)) } }