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

How to remove a localStorage key entirely? #7

Closed rightaway closed 8 years ago

rightaway commented 9 years ago

I'm using the latest beta of 1.0. How can I remove a localStorage key entirely, as opposed to just setting the value to be {}? In my reducer if I delete the key from the state, like delete state.localstoragekey then localstoragekey still has a value of {} instead of not appearing in the localStorage list at all.

elgerlambert commented 9 years ago

Hi @rightaway, the first thing that comes to my mind would be to create a storage enhancer that checks whether the state is an empty object and if so remove it from storage:

export default function clearIfEmpty(storage) {
  return ({
    ...storage,
    put: (key, state, callback) => {
      if (_.empty(state)) return storage.del(key)
      storage.put(key, state, callback)
    }
  })
}

Make sure you add it after the filter storage enhancer in case you're using it:

const storage = compose(
  filter('key'),
  clearIfEmpty
)(adapter(localStorage));

Out of curiosity, does the empty object in localStorage create an issue or do you simply want to be tidy?

rightaway commented 9 years ago

Thanks for the detailed response. Would you consider making that the default behavior in a future version so it doesn't need to be done manually? (Can't think of a situation where having the empty key sticking around would be the desired behavior.)

Out of curiosity, does the empty object in localStorage create an issue or do you simply want to be tidy?

Mostly to keep it tidy (although there was an issue with thinking the value existed since the key was still around) because throughout the app several different keys are created and cleared, so the clutter would build up over usage of the app.