dmulay360
dmulay360

Reputation: 23

How to use useAsyncStorage to set the state of an array

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>
  );
}

Upvotes: 1

Views: 207

Answers (2)

Ben Taber
Ben Taber

Reputation: 6741

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 deserialize using JSON.parse(myObj) immediately after reading from stroage.

Upvotes: 1

Jaid
Jaid

Reputation: 181

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

Upvotes: 0

Related Questions