mrousavy / react-native-mmkv

⚡️ The fastest key/value storage for React Native. ~30x faster than AsyncStorage!
https://mrousavy.com
MIT License
6.17k stars 258 forks source link

Set new key value returns undefined value at listener #324

Closed cyim02 closed 2 years ago

cyim02 commented 2 years ago

When I tried to use a listener,

useEffect(() => {
  const listener = storage.addOnValueChangedListener((changedKey) => {
    const newValue = storage.getString(changedKey)
    console.log(`"${changedKey}" new value: ${newValue}`)
  })
  // cleanup function
  return () => {
    listener.remove()
  }
}, [storage])

Setting new key value pairs would return undefined at newValue. Updating existing key value pairs works fine.

Is this an expected behavior?

Thanks!

mrousavy commented 2 years ago

Hmm, are you sure you're setting strings? I'll take a look!

cyim02 commented 2 years ago

Hmm, are you sure you're setting strings? I'll take a look!

@mrousavy Thanks for the reply! I have tried both short pure string and large JSON with JSON.stringify. Both have the same undefined result for the code above. I did the testing in the root function so that it is not something related to navigation caching or the "memo" stuff. Then, I tried to re-render the function once after setting new key value pairs to see if the getString works. It appears that the new data did appear after the re-rendering. Just not right after the addOnValueChangedListener executes.

mrousavy commented 2 years ago

Can you see if #326 fixes the issue for you?

cyim02 commented 2 years ago

@mrousavy Thanks for the quick response! I tried to npm install the fix branch (npm install mrousavy/react-native-mmkv#fix/fix-callbacks), but not sure why I went into the following errors:

the package `F:\project\mobile\node_modules\react-native-mmkv\package.json` was successfully found. 
However, this package itself specifies a `main` module field that could not be resolved 
(`F:\project\mobile\node_modules\react-native-mmkv\lib\module\index`).

I do believe this is not related to this library. And I did clear all the cache, even killed all running servers and restarted, but still no luck.

I think I might miss some important steps or methods. May I know how I should test this out? Or else maybe I will wait for another release with the fix and update the library through npm/yarn.

Highly appreciated~

ramirobg94 commented 2 years ago

+1

mrousavy commented 2 years ago

Fixed & Released in v2.3.3 🎉

mrousavy commented 2 years ago

If you appreciate my efforts please consider sponsoring me on GitHub so I can have more time in the future to work on issues like these. 🙏

cyim02 commented 2 years ago

If you appreciate my efforts please consider sponsoring me on GitHub so I can have more time in the future to work on issues like these. 🙏

@mrousavy Really appreciate your effort! I will keep an eye on this if my project receives sufficient funding 💪