nbubna / store

A better way to use localStorage and sessionStorage
MIT License
1.91k stars 109 forks source link

Feature request: Force fake mode #94

Closed TrevorBurnham closed 2 years ago

TrevorBurnham commented 3 years ago

For some purposes, it'd be nice to use store2's fake localStorage mode even when localStorage is available. My particular use case is a Storybook that runs in an iframe: Storybook's use of localStorage prevents me from configuring it in each iframe independently (unless I serve each iframed Storybook instance from a different domain).

Proposed API:

store.isFake(); // => false
store.get('foo'); // => "value"
store.forceFakeMode(true); // new API
store.isFake(); // => true
store.get('foo'); // => undefined

The actual localStorage would not be affected; the in-memory storage would just be used instead.

nbubna commented 3 years ago

Interesting. Do you expect this would affect all areas? So store.session.isFake() would return true after calling store.forceFake()? And would you be able to turn off fake mode w/o reloading the page? Like store.forceFake(false)?

My inclination would be no, only have it affect the current area. In fact, the easiest way to implement it would be to replace the area it was called on with a fake one, of course, that's not as trivial to reverse, so i'd probably just have it be forceFake() with no args, unless there was call for turning it off again.

You could probably mimic what i'm picturing by with an extension like:

store._.fn('forceFake', function() { this.area = .storage('fake');// uses an internal prop '_area' })

Then you could call

store.session.forceFake()

And only sessionStorage would be superseded with fake storage.

I haven't tested that, but i think it'd do the trick.

I think this is small enough to be worth considering adding in the next release. Leave this issue open until i do that or change my mind. :)

TrevorBurnham commented 3 years ago

Aha, that works! Slightly modified for posterity:

// Register forceFake extension
store._.fn('forceFake', function() {
  this._area = store._.storage('fake');
});

// Force fake localStorage
store.local.forceFake();

// Force fake sessionStorage
store.session.forceFake();

Thanks for your help. 👍

TrevorBurnham commented 3 years ago

Reopening re:

I think this is small enough to be worth considering adding in the next release. Leave this issue open until i do that or change my mind. :)