2222
2323## ` getItem `
2424
25- Fetches a data for a given ` key ` , invokes (optional) callback once completed.
25+ Gets a string value for given ` key ` . This function can either return a string value for existing ` key ` or return ` null ` otherwise.
26+
27+ In order to store object value, you need to deserialize it, e.g. using ` JSON.parse() ` .
28+
29+ * Note (legacy)* : you can use optional callback as an alternative for returned promise.
2630
2731** Signature** :
2832
@@ -32,15 +36,32 @@ static getItem(key: string, [callback]: ?(error: ?Error, result: ?string) => voi
3236
3337**Returns**:
3438
35- ` Promise ` with data, if exists, ` null ` otherwise.
39+ ` Promise ` resolving with a string value, if entry exists for given ` key ` , or ` null ` otherwise.
40+
41+ ` Promise ` can be also rejects in case of underlying storage error.
3642
3743**Example**:
3844
3945` ` ` js
4046
41- getMyValue = async () => {
47+ getMyStringValue = async () => {
48+ try {
49+ return await AsyncStorage .getItem (' @key' )
50+ } catch (e) {
51+ // read error
52+ }
53+
54+ console .log (' Done.' )
55+
56+ }
57+ ` ` `
58+
59+ ` ` ` js
60+
61+ getMyObject = async () => {
4262 try {
43- const value = await AsyncStorage .getItem (' @MyApp_key' )
63+ const jsonValue = await AsyncStorage .getItem (' @key' )
64+ return jsonValue != null ? JSON .parse (jsonValue) : null
4465 } catch (e) {
4566 // read error
4667 }
@@ -58,7 +79,11 @@ getMyValue = async () => {
5879
5980## ` setItem `
6081
61- Stores a ` value ` for the ` key ` , invokes (optional) ` callback ` once completed.
82+ Sets a string ` value ` for given ` key ` . This operation can either modify an existing entry, if it did exist for given ` key ` , or add new one otherwise.
83+
84+ In order to store object value, you need to serialize it, e.g. using ` JSON .stringify ()` .
85+
86+ *Note (legacy)*: you can use optional callback as an alternative for returned promise.
6287
6388**Signature**:
6489
@@ -68,15 +93,31 @@ static setItem(key: string, value: string, [callback]: ?(error: ?Error) => void)
6893
6994**Returns**:
7095
71- ` Promise ` object.
96+ ` Promise ` resolving when the set operation is completed.
97+
98+ ` Promise ` can be also rejects in case of underlying storage error.
7299
73100**Example**:
74101
75102` ` ` js
76103
77- setValue = async () => {
104+ setStringValue = async (value ) => {
105+ try {
106+ await AsyncStorage .setItem (' key' , value)
107+ } catch (e) {
108+ // save error
109+ }
110+
111+ console .log (' Done.' )
112+ }
113+ ` ` `
114+
115+ ` ` ` js
116+
117+ setObjectValue = async (value ) => {
78118 try {
79- await AsyncStorage .setItem (' @MyApp_key' , ' my secret value' )
119+ const jsonValue = JSON .stringify (value)
120+ await AsyncStorage .setItem (' key' , jsonValue)
80121 } catch (e) {
81122 // save error
82123 }
0 commit comments