rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

[storage] update all storage engines to use promise instead of callback #450

Open rt2zz opened 6 years ago

rt2zz commented 6 years ago

In 5.0.0-beta.13 we converted from callback to promise. This is going to be a painful change as all storage engines will need to be updated, however better to bite the bullet now as longer term it will make the code easier to maintain and less bytes.

williamoliveira commented 6 years ago

I made a little adapter to keep using old callback based storage engines before they update

const promisefy = fn => (...args) => new Promise((resolve, reject) => {
  fn(...args, (err, result) => (err ? reject(err) : resolve(result)))
})

const storageAdapter = storage => ({
  getItem: promisefy(storage.getItem),
  setItem: promisefy(storage.setItem),
  removeItem: promisefy(storage.removeItem),
  getAllKeys: promisefy(storage.getAllKeys),
})
rt2zz commented 6 years ago

thank you for sharing this, mind if we ship this utility in redux-persist? im thinking it could live at import storageCallbackAdapter from 'redux-persist/lib/integration/storageCallbackAdapter'

williamoliveira commented 6 years ago

Sure, just one thing, I actually had to bind every method for a class based storage because I was getting an error in a place it was using this, not sure if it is the correct thing to do tho, my js abilities only go so far

// ...
const storageAdapter = storage => ({
  getItem: promisefy(storage.getItem.bind(storage)),
  setItem: promisefy(storage.setItem.bind(storage)),
  removeItem: promisefy(storage.removeItem.bind(storage)),
  getAllKeys: promisefy(storage.getAllKeys.bind(storage)),
})
leethree commented 6 years ago

I just wrote a storage engine based on react-native-fs that supports both Promise and callback. Would love to hear your feedback:

https://github.com/leethree/redux-persist-fs-storage

rt2zz commented 6 years ago

awesome! added to the readme https://github.com/rt2zz/redux-persist/tree/v5