Home > Software design >  How to use useAsyncStorage to set the state of an array
How to use useAsyncStorage to set the state of an array

Time:01-06

I have this code from the async storage docs. However, this only works for setting the state of string values. How can I do with an array of objects?

export default function App() {
  const [value, setValue] = useState('value');
  const { getItem, setItem } = useAsyncStorage('@storage_key');

  const readItemFromStorage = async () => {
    const item = await getItem();
    setValue(item);
  };

  const writeItemToStorage = async newValue => {
    await setItem(newValue);
    setValue(newValue);
  };

  useEffect(() => {
    readItemFromStorage();
  }, []);

  return (
    <View style={{ margin: 40 }}>
      <Text>Current value: {value}</Text>
      <TouchableOpacity
        onPress={() =>
          writeItemToStorage(
            Math.random()
              .toString(36)
              .substr(2, 5)
          )
        }
      >
        <Text>Update value</Text>
      </TouchableOpacity>
    </View>
  );
}

CodePudding user response:

The usage docs mention that only string data can be stored.

See https://react-native-async-storage.github.io/async-storage/docs/usage

To store an Object or Array, you'll need to serialize it using JSON.stringify(myObj) prior to writing to storage, and deserilize using JSON.parse(myObj) immediately after reading from stronage.

CodePudding user response:

You can use JSON.parse(retrievedItemFromStorage) to parse it to an Array/Object

  •  Tags:  
  • Related