elgerlambert / redux-localstorage

Store enhancer that syncs (a subset) of your Redux store state to localstorage.
MIT License
1.32k stars 107 forks source link

Handle exceeding the localStorage quotum #65

Open ismay opened 7 years ago

ismay commented 7 years ago

Out of curiosity, does this library handle the (unlikely) event of a user exceeding the localStorage quotum in a session? From what I understand (http://stackoverflow.com/a/14191200/5918874) in that case an exception will be thrown and no new data will be written.

Theoretically it could be possible since users can set the maximum themselves, or the device could be limited in available space.

DiesIrae commented 6 years ago

On last version It fails completely when quotum is exceeded.

It's a real-world problem because some browsers have no quotum (private navigation in Safari for ex.)

DiesIrae commented 6 years ago

For anyone having the same problem, here is my dirty solution :

import _ from "lodash"
import persistState, { mergePersistedState } from 'redux-localstorage'
import adapter from 'redux-localstorage/lib/adapters/localStorage';

const storage = window.localStorage

...

const isStorageOk = () => {
  try {
    storage.setItem("test", "1");
    storage.removeItem("test");
    return true
  }
  catch(e) {
    console.warn("No local storage", e)
  }
}

const storageAdapter = adapter(storage)

const enhancers = _.compact([
  applyMiddleware(...middlewares),
  isStorageOk() && persistState(storageAdapter, storageKey)
])

const enhancer = composeEnhancers(...enhancers)

export const store = createStore(reducer, enhancer)