diff --git a/lib/storage/providers/LocalForage.js b/lib/storage/providers/LocalForage.js index 3a8c4634a..431f3a24b 100644 --- a/lib/storage/providers/LocalForage.js +++ b/lib/storage/providers/LocalForage.js @@ -12,6 +12,43 @@ localforage.config({ name: 'OnyxDB' }); +class SynchronousWriteQueue { + constructor() { + this.isWriting = false; + this.queue = []; + } + + push(item) { + this.queue.push(item); + this.process(); + } + + process() { + if (this.isWriting) { + return; + } + + this.isWriting = true; + const next = this.queue.shift(); + if (!next) { + this.isWriting = false; + return; + } + + const { + key, value, resolve, reject, + } = next; + localforage.setItem(key, value) + .then(resolve) + .catch(reject) + .finally(() => { + this.isWriting = false; + this.process(); + }); + } +} + +const pairQueue = new SynchronousWriteQueue(); const provider = { /** * Get multiple key-value pairs for the give array of keys in a batch @@ -90,7 +127,11 @@ const provider = { * @param {*} value * @return {Promise} */ - setItem: localforage.setItem, + setItem: (key, value) => new Promise((resolve, reject) => { + pairQueue.push({ + key, value, resolve, reject, + }); + }), }; export default provider;