Search code examples
reactjsreact-nativeasyncstorage

Formatting data retrieved from asyncStorage in react native


I am storing some data in asyncStorage via @react-native-async-storage/async-storage in my 'react-native' app. When I pull the data back out I want to assign the results to a drop-menu list, which expects this format:

names = [{name: 'Dave'}, {name: 'Julio'}];

Right now when I pull out the asyncStorage data, and apply JSON.parse(), it looks like this:

jsonNames:  Array [
  "{\"name\":\"Chris\"}",
  "{\"name\":\"Janet\"}",
  "{\"name\":\"Augustine\"}",
]

This is my function to retrieve the data:

  getNames = async () => {
    try {
      const jsonNames = await AsyncStorage.getItem('names')
      return jsonNames != null ? JSON.parse(jsonNames) : null;
    } catch(e) {
      console.log(e);
    }
  }

Is there a function I can use to clean this up so that it's in the format I need, as described above?


Solution

  • to convert it do addition step like this

    const jsonNames = [
      "{\"name\":\"Chris\"}",
      "{\"name\":\"Janet\"}",
      "{\"name\":\"Augustine\"}",
    ];
    
    console.log(jsonNames.map(x => JSON.parse(x)))

    also, you can review the way you use to save this value in AsyncStorage it is look lik you serialize every object on array Separately before saving, not the whole array once.