Search code examples
react-nativereact-native-iosasyncstorage

AsyncStorage works on react-native-web, fails on ios (stringified json data)


I have a web/ios react-native project. On web this works without any issue, but on iOS I am getting an error. Strangely, I dont see the error at all in the debug window, so I have to rely on the red screen.

The way I am saving the data is like this:

console.log(`user progress: writing string of >>${JSON.stringify(user.progress)}<< original's type: '${typeof user.progress}'`)
await AsyncStorage.setItem(
    appConfig.constants.graphcool.progress,
    user.progress
)

And that log is the last log I see in the debugger:

user progress: writing string of >>{"VocabularyPairs":{"1":0.984375,"2":0.996875,"3":0.875}}<< original's type: 'object'

I am getting a red screen with error in iOS:

Exception '-[NSDictionaryM length]: unrecognized selector sent to instance 0x2832c5ce0' was thrown while invoking multiSet on target AsyncLocalStorage with params (
    (
        (
      progress,
            {
        VocabularyPairs =        {
          1 = "0.984375";
          2 = "0.996875";
          3 = "0.875";
        };
      }
    )
  ),
  311
)

So -- I can fix this by changing the code:

await AsyncStorage.setItem(
    appConfig.constants.graphcool.progress,
    Platform.OS === 'ios' ? JSON.stringify(user.progress): user.progress
)

But my question is, why do I have to? If I do fix it, there are two other places that also set this same item -- one already has that wrapper, the other does not. Both work, and it is always almost the same data -- the numbers (that is, the values) may change, but they are string-keys and number values everywhere.

What makes the first write special?


Solution

  • If you are using AsyncStorage.setItem value should be a string. Passing object instead of string should not work!

      AsyncStorage.setItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
    

    REFERE DOCS HERE