Skip to content

Commit 239cf7e

Browse files
committed
docs: migration, usage
1 parent b5a7ea6 commit 239cf7e

File tree

5 files changed

+205
-24
lines changed

5 files changed

+205
-24
lines changed

docs/api/errors.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Error handling
2+
3+
4+
todo

docs/api/usage.md

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
---
2+
title: Usage
3+
---
4+
5+
# Using Async Storage
6+
7+
The [`AsyncStorage`](https://github.com/react-native-async-storage/async-storage/blob/main/packages/async-storage/src/AsyncStorage.ts) interface provides an asynchronous, promise-based API for persistent key-value storage.
8+
Each method is modeled after the Web Storage API, with extensions for batch operations.
9+
10+
Similar to Web, AsyncStorage deals with data that should be already serialized (strings). If you need to store objects, arrays, or other non-string values, you must serialize them first (for example, using `JSON.stringify`) and deserialize them when retrieving (for example, using `JSON.parse`).
11+
12+
## Creating a storage
13+
14+
To create a new storage, call `createAsyncStorage` with your database name:
15+
16+
```typescript
17+
import { createAsyncStorage } from "@react-native-async-storage/async-storage";
18+
19+
// any name is fine, you can even add an extension!
20+
const userStorage = createAsyncStorage("john.db");
21+
```
22+
23+
This returns an instance of `AsyncStorage` and each instance is uniquely identified by the name you provide.
24+
The data in one storage instance is scoped to its name: using different names ensures that data does not leak between storages.
25+
26+
!!! note "Web platform"
27+
28+
On Web, AsyncStorage is backed by [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API), which also support scoped storages.
29+
30+
!!! warning "Windows platform"
31+
32+
As of AsyncStorage v3.0, Windows platform does not support scoped storages. It fallsback to previous implementation - single storage per application.
33+
34+
## Using a storage
35+
36+
Once you have created a storage instance, you can start managing data.
37+
38+
### Single item operations
39+
40+
You can store, retrieve, and remove individual keys using `setItem`, `getItem`, and `removeItem`.
41+
42+
Note that:
43+
44+
- Calling `setItem` with an existing key will overwrite the current value
45+
- Calling `removeItem` on a key that does not exist has no effect and does not throw an error
46+
47+
```typescript
48+
await userStorage.setItem("username", "doe_john");
49+
// previously stored value is overriden
50+
await userStorage.setItem("username", "john_doe");
51+
52+
// read current value
53+
let username = await userStorage.getItem("username");
54+
console.log(username); // "john_doe"
55+
56+
await userStorage.removeItem("username");
57+
// does nothing, item is already removed
58+
await userStorage.removeItem("username");
59+
60+
username = await userStorage.getItem("username");
61+
console.log(username); // null
62+
```
63+
64+
### Batch operations
65+
66+
Use convenient batch methods to handle multiple keys at once. Behind the scene, transaction performed to store all of them, or none in case of an error.
67+
68+
```typescript
69+
// store values
70+
await userStorage.setMany({
71+
72+
age: "30",
73+
});
74+
75+
// read multiple items
76+
const data = await userStorage.getMany(["email", "age", "username"]);
77+
console.log(data);
78+
// {
79+
// email: "[email protected]",
80+
// age: "30",
81+
// username: null, // key doesn't exist
82+
// }
83+
84+
// remove multiple items
85+
// non-existing keys are ignored
86+
await userStorage.removeMany(["email", "age", "not-here"]);
87+
```
88+
89+
### Reading stored keys
90+
91+
To retrieve all keys currently stored in a storage instance, use `getAllKeys`:
92+
93+
```typescript
94+
await userStorage.setMany({
95+
96+
age: "30",
97+
});
98+
99+
const keys = await userStorage.getAllKeys();
100+
console.log(keys); // ["email", "age"]
101+
```
102+
103+
### Clearing storage
104+
105+
To remove all data from a storage instance, use `clear`:
106+
107+
```typescript
108+
await userStorage.setMany({
109+
110+
age: "30",
111+
});
112+
113+
await userStorage.clear();
114+
const keys = await userStorage.getAllKeys();
115+
console.log(keys); // []
116+
```

docs/index.md

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
title: Overview
3+
---
4+
15
# Async Storage
26

37
Async Storage is asynchronous, unencrypted, persistent, key-value storage for your React Native application.
@@ -34,12 +38,10 @@ pod install
3438

3539
## Usage
3640

37-
### Basic
38-
3941
```typescript
4042
import { createAsyncStorage } from "@react-native-async-storage/async-storage";
4143

42-
// Create a storage instance
44+
// create a storage instance
4345
const storage = createAsyncStorage("appDB");
4446

4547
async function demo() {
@@ -48,30 +50,11 @@ async function demo() {
4850

4951
// read value stored at "userToken" key
5052
const token = await storage.getItem("userToken");
51-
console.log("Stored token:", token);
53+
console.log("Stored token:", token); // abc123
5254

5355
// remove value from storage
5456
await storage.removeItem("userToken");
5557
}
5658
```
5759

58-
### Multi-item operations
59-
60-
Async Storage supports batch operations for efficiency:
61-
62-
```typescript
63-
async function demo() {
64-
// save multiple values at once
65-
await storage.setMany({
66-
theme: "dark",
67-
language: "en",
68-
});
69-
70-
// Retrieve multiple values
71-
const values = await storage.getMany(["theme", "language", "different"]);
72-
console.log(values); // { theme: "dark", language: "en", different: null }
73-
74-
// Remove multiple values
75-
await storage.removeMany(["theme", "language"]);
76-
}
77-
```
60+
Head over to [Usage page](api/usage.md) to learn more.

docs/migration-to-3.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Migration to v3
2+
3+
AsyncStorage v3 introduces some breaking changes to simplify the API and make it more consistent.
4+
5+
## AsyncStorage instance needs to be created now
6+
7+
AsyncStorage v3 introduced scoped storages, which needs to be created before use. Head to [Usage page](api/usage.md#creating-a-storage) to learn more.
8+
9+
## Default export points to v2 storage
10+
11+
To make transition easier, the default export still points to the v2 storage implementation, ensuring that no existing data is lost.
12+
13+
## Removed callback arguments
14+
15+
All methods now return Promises, and callbacks have been removed from all methods.
16+
17+
## Removed merge functionality
18+
19+
AsyncStorage's "merge" behavior has historically been inconsistent across platforms. Rather than enforcing a platform-specific merging strategy, the merge API has been removed to avoid ambiguity.
20+
21+
## Method signature changes
22+
23+
The core methods
24+
25+
- `getItem`
26+
- `setItem`
27+
- `removeItem`
28+
- `getAllKeys`
29+
- `clear`
30+
31+
retain their signatures from v2, ensuring backward compatibility.
32+
33+
### multiGet
34+
35+
Renamed to `getMany` and returns a `Record<string, string | null>`, following a "what you request is what you get" rule: every key you pass in the request appears in the returned object, with `null` for keys that don’t exist in storage.
36+
37+
```diff
38+
- multiGet: (
39+
- keys: readonly string[],
40+
- callback?: MultiGetCallback
41+
- ) => Promise<readonly KeyValuePair[]>;
42+
43+
+ getMany(keys: string[]): Promise<Record<string, string | null>>;
44+
```
45+
46+
### multiSet
47+
48+
Renamed to `setMany`, accepts a `Record<string, string>` of key-value entries.
49+
50+
```diff
51+
- multiSet: (
52+
- keyValuePairs: ReadonlyArray<readonly [string, string]>,
53+
- callback?: MultiCallback
54+
- ) => Promise<void>;
55+
56+
+ setMany(entries: Record<string, string>): Promise<void>;
57+
```
58+
59+
### multiRemove
60+
61+
Renamed to `removeMany`, accepts list of keys.
62+
63+
```diff
64+
- multiRemove: (
65+
- keys: readonly string[],
66+
- callback?: MultiCallback
67+
- ) => Promise<void>;
68+
69+
+ removeMany(keys: string[]): Promise<void>;
70+
```
71+
72+
## Errors are more predictable now
73+
74+
All errors now thrown from `AsyncStorage` are instances of `AsyncStorageError` containing `type` of the error it represents. Head over to [Errors page](api/errors.md) to learn more.

mkdocs.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ site_url: https://react-native-async-storage.github.io/
44

55
nav:
66
- Overview: index.md
7+
- API:
8+
- Usage: api/usage.md
9+
- 'Error handling': api/errors.md
10+
- 'Migration to v3': migration-to-3.md
711
- Changelog: changelog.md
812

913

0 commit comments

Comments
 (0)