Skip to content

Commit

Permalink
Merge pull request #96 from parasharrajat/fix-render
Browse files Browse the repository at this point in the history
fix Breaking Changes for `initWithStoredValues` 🏴
  • Loading branch information
Joel Bettner authored Aug 12, 2021
2 parents d7553b9 + ac78417 commit 0737603
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions lib/Onyx.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,9 @@ function keysChanged(collectionKey, collection) {
*
* @param {string} key
* @param {mixed} data
* @param {boolean} [hasNewValue=true]
*/
function keyChanged(key, data) {
function keyChanged(key, data, hasNewValue = true) {
// Add or remove this key from the recentlyAccessedKeys lists
if (!_.isNull(data)) {
addLastAccessedKey(key);
Expand All @@ -282,6 +283,11 @@ function keyChanged(key, data) {
// Find all subscribers that were added with connect() and trigger the callback or setState() with the new data
_.each(callbackToStateMapping, (subscriber) => {
if (subscriber && isKeyMatch(subscriber.key, key)) {
// If data is not new then only trigger the callback or setState() for subscribers
// which are not initialized with Stored value
if (!hasNewValue && (subscriber.initWithStoredValues !== false)) {
return;
}
if (_.isFunction(subscriber.callback)) {
subscriber.callback(data, key);
}
Expand Down Expand Up @@ -475,16 +481,19 @@ function evictStorageAndRetry(error, ionMethod, ...args) {
* @returns {Promise}
*/
function set(key, val) {
// Skip writing to storage if the value hasn't changed
if (cache.hasCacheForKey(key) && _.isEqual(val, cache.getValue(key))) {
return Promise.resolve();
}
const shouldCacheNewValue = !cache.hasCacheForKey(key) || !_.isEqual(val, cache.getValue(key));

// Adds the key to cache when it's not available
cache.set(key, val);
if (shouldCacheNewValue) {
cache.set(key, val);
}

// Optimistically inform subscribers on the next tick
Promise.resolve().then(() => keyChanged(key, val));
Promise.resolve().then(() => keyChanged(key, val, shouldCacheNewValue));

if (!shouldCacheNewValue) {
return Promise.resolve();
}

// Write the thing to persistent storage, which will trigger a storage event for any other tabs open on this domain
return AsyncStorage.setItem(key, JSON.stringify(val))
Expand Down

0 comments on commit 0737603

Please sign in to comment.