• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# LocalStorage: UI State Storage
2
3
4LocalStorage provides storage for the page-level UI state. The parameters of the LocalStorage type accepted through the \@Entry decorator share the same LocalStorage instance on the page. LocalStorage also allows for state sharing between pages within a UIAbility.
5
6
7This topic describes only the LocalStorage application scenarios and related decorators: \@LocalStorageProp and \@LocalStorageLink.
8
9
10> **NOTE**
11>
12> LocalStorage is supported since API version 9.
13
14
15## Overview
16
17LocalStorage is an in-memory "database" that ArkTS provides for storing state variables that are required to build pages of the application UI.
18
19- An application can create multiple LocalStorage instances. These instances can be shared on a page or, by using the **GetShared** API from the UIAbility, across pages in a UIAbility.
20
21- The root node of a component tree, that is, the \@Component decorated by \@Entry, can be assigned to a LocalStorage instance. All child instances of this custom component automatically gain access to the same LocalStorage instance.
22
23- An \@Component decorated component has access to at most one LocalStorage instance and to [AppStorage](arkts-appstorage.md). A component not decorated with \@Entry cannot be assigned a LocalStorage instance. It can only accept a LocalStorage instance passed from its parent component through \@Entry. A LocalStorage instance can be assigned to multiple components in the component tree.
24
25- All attributes in LocalStorage are mutable.
26
27The application determines the lifecycle of a LocalStorage object. The JS Engine will garbage collect a LocalStorage object when the application releases the last reference to it, which includes deleting the last custom component.
28
29LocalStorage provides two decorators based on the synchronization type of the component decorated with \@Component:
30
31- [@LocalStorageProp](#localstorageprop): \@LocalStorageProp creates a one-way data synchronization from the named attribute in LocalStorage to the \@LocalStorageProp decorated variable.
32
33- [@LocalStorageLink](#localstoragelink): \@LocalStorageLink creates a two-way data synchronization with the named attribute in the \@Component's LocalStorage.
34
35
36## Restrictions
37
38- Once created, the type of a named attribute cannot be changed. Subsequent calls to **Set** must set a value of same type.
39- LocalStorage provides page-level storage. The [GetShared](../reference/arkui-ts/ts-state-management.md#getshared9) API can only obtain the LocalStorage instance transferred through [windowStage.loadContent](../reference/apis/js-apis-window.md#loadcontent9) in the current stage. Otherwise, **undefined** is returned. Example: [Sharing a LocalStorage Instance from UIAbility to One or More Pages](#sharing-a-localstorage-instance-from-uiability-to-one-or-more-pages).
40
41
42## \@LocalStorageProp
43
44As mentioned above, if you want to establish a binding between LocalStorage and a custom component, you need to use the \@LocalStorageProp and \@LocalStorageLink decorators. Use \@LocalStorageProp(key) or \@LocalStorageLink(key) to decorate variables in the component. **key** identifies the attribute in LocalStorage.
45
46
47When a custom component is initialized, the \@LocalStorageProp(key)/\@LocalStorageLink(key) decorated variable is initialized with the value of the attribute with the given key in LocalStorage. Local initialization is mandatory. If an attribute with the given key is missing from LocalStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in LocalStorage depends on the application logic.)
48
49
50> **NOTE**
51>
52> Since API version 9, this decorator is supported in ArkTS widgets.
53
54
55By decorating a variable with \@LocalStorageProp(key), a one-way data synchronization is established with the attribute with the given key in LocalStorage. A local change can be made, but it will not be synchronized to LocalStorage. An update to the attribute with the given key in LocalStorage will overwrite local changes.
56
57
58### Rules of Use
59
60| \@LocalStorageProp Decorator| Description                                      |
61| ----------------------- | ---------------------------------------- |
62| Decorator parameters                  | **key**: constant string, mandatory (note, the string is quoted)                 |
63| Allowed variable types              | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.|
64| Synchronization type                   | One-way: from the attribute in LocalStorage to the component variable. The component variable can be changed locally, but an update from LocalStorage will overwrite local changes.|
65| Initial value for the decorated variable              | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.|
66
67
68### Variable Transfer/Access Rules
69
70| Transfer/Access     | Description                                      |
71| ---------- | ---------------------------------------- |
72| Initialization and update from the parent component| Forbidden.|
73| Subnode initialization    | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
74| Access | None.                                      |
75
76  **Figure 1** \@LocalStorageProp initialization rule
77
78![en-us_image_0000001501936014](figures/en-us_image_0000001501936014.png)
79
80
81### Observed Changes and Behavior
82
83**Observed Changes**
84
85
86- When the decorated variable is of the Boolean, string, or number type, its value change can be observed.
87
88- When the decorated variable is of the class or Object type, its value change and value changes of all its attributes, that is, the attributes that **Object.keys(observedObject)** returns.
89
90- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed.
91
92
93**Framework Behavior**
94
95
96- When the value change of the \@LocalStorageProp(key) decorated variable is observed, the change is not synchronized to the attribute with the give key value in LocalStorage.
97
98- The value change of the \@LocalStorageProp(key) decorated variable only applies to the private member variables of the current component, but not other variables bound to the key.
99
100- When the data decorated by \@LocalStorageProp(key) is a state variable, the change of the data is not synchronized to LocalStorage, but the owning custom component is re-rendered.
101
102- When the attribute with the given key in LocalStorage is updated, the change is synchronized to all the \@LocalStorageProp(key) decorated data, and the local changes of the data are overwritten.
103
104
105## \@LocalStorageLink
106
107\@LocalStorageLink is required if you need to synchronize the changes of the state variables in a custom component back to LocalStorage.
108
109\@LocalStorageLink(key) creates a two-way data synchronization with the attribute with the given key in LocalStorage.
110
1111. If a local change occurs, it is synchronized to LocalStorage.
112
1132. Changes in LocalStorage are synchronized to all attributes with the given key, including one-way bound variables (\@LocalStorageProp decorated variables and one-way bound variables created through \@Prop) and two-way bound variables (\@LocalStorageLink decorated variables and two-way bound variables created through \@Link).
114
115
116### Rules of Use
117
118| \@LocalStorageLink Decorator| Description                                      |
119| ----------------------- | ---------------------------------------- |
120| Decorator parameters                  | **key**: constant string, mandatory (note, the string is quoted)                 |
121| Allowed variable types              | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.|
122| Synchronization type                   | Two-way: from the attribute in LocalStorage to the custom component variable and back|
123| Initial value for the decorated variable              | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.|
124
125
126### Variable Transfer/Access Rules
127
128| Transfer/Access     | Description                                      |
129| ---------- | ---------------------------------------- |
130| Initialization and update from the parent component| Forbidden.|
131| Subnode initialization    | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
132| Access | None.                                      |
133
134
135  **Figure 2** \@LocalStorageLink initialization rule
136
137
138![en-us_image_0000001552855957](figures/en-us_image_0000001552855957.png)
139
140
141### Observed Changes and Behavior
142
143**Observed Changes**
144
145
146- When the decorated variable is of the Boolean, string, or number type, its value change can be observed.
147
148- When the decorated variable is of the class or Object type, its value change and value changes of all its attributes, that is, the attributes that **Object.keys(observedObject)** returns.
149
150- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed.
151
152
153**Framework Behavior**
154
155
1561. When the value change of the \@LocalStorageLink(key) decorated variable is observed, the change is synchronized to the attribute with the give key value in LocalStorage.
157
1582. Once the attribute with the given key in LocalStorage is updated, all the data (including \@LocalStorageLink and \@LocalStorageProp decorated variables) bound to the attribute key is changed synchronously.
159
1603. When the data decorated by \@LocalStorageProp(key) is a state variable, the change of the data is synchronized to LocalStorage, and the owning custom component is re-rendered.
161
162
163## Application Scenarios
164
165
166### Example of Using LocalStorage in Application Logic
167
168
169```ts
170let storage = new LocalStorage({ 'PropA': 47 }); // Create a new instance and initialize it with the given object.
171let propA = storage.get('PropA') // propA == 47
172let link1 = storage.link('PropA'); // link1.get() == 47
173let link2 = storage.link('PropA'); // link2.get() == 47
174let prop = storage.prop('PropA'); // prop.get() = 47
175link1.set(48); // two-way sync: link1.get() == link2.get() == prop.get() == 48
176prop.set(1); // one-way sync: prop.get()=1; but link1.get() == link2.get() == 48
177link1.set(49); // two-way sync: link1.get() == link2.get() == prop.get() == 49
178```
179
180
181### Example for Using LocalStorage from Inside the UI
182
183The two decorators \@LocalStorageProp and \@LocalStorageLink can work together to obtain the state variable stored in a LocalStorage instance in the UI component.
184
185This example uses \@LocalStorage as an example to show how to:
186
187- Use the **build** function to create a LocalStorage instance named **storage**.
188
189- Use the \@Entry decorator to add **storage** to the top-level component **CompA**.
190
191- Use \@LocalStorageLink to create a two-way data synchronization with the given attribute in LocalStorage.
192
193  ```ts
194  // Create a new instance and initialize it with the given object.
195  let storage = new LocalStorage({ 'PropA': 47 });
196
197  @Component
198  struct Child {
199    // @LocalStorageLink creates a two-way data synchronization with the ProA attribute in LocalStorage.
200    @LocalStorageLink('PropA') storLink2: number = 1;
201
202    build() {
203      Button(`Child from LocalStorage ${this.storLink2}`)
204        // The changes will be synchronized to ProA in LocalStorage and with Parent.storLink1.
205        .onClick(() => this.storLink2 += 1)
206    }
207  }
208  // Make LocalStorage accessible from the @Component decorated component.
209  @Entry(storage)
210  @Component
211  struct CompA {
212    // @LocalStorageLink creates a two-way data synchronization with the ProA attribute in LocalStorage.
213    @LocalStorageLink('PropA') storLink1: number = 1;
214
215    build() {
216      Column({ space: 15 }) {
217        Button(`Parent from LocalStorage ${this.storLink1}`) // initial value from LocalStorage will be 47, because 'PropA' initialized already
218          .onClick(() => this.storLink1 += 1)
219        // The @Component decorated child component automatically obtains access to the CompA LocalStorage instance.
220        Child()
221      }
222    }
223  }
224  ```
225
226
227### Simple Example of Using \@LocalStorageProp with LocalStorage
228
229In this example, the **CompA** and **Child** components create local data that is one-way synced with the PropA attribute in the LocalStorage instance **storage**.
230
231- The change of **this.storProp1** in **CompA** takes effect only in **CompA** and is not synchronized to **storage**.
232
233- In the **Child** component, the value of **storProp2** bound to **Text** is still 47.
234
235  ```ts
236  // Create a new instance and initialize it with the given object.
237  let storage = new LocalStorage({ 'PropA': 47 });
238  // Make LocalStorage accessible from the @Component decorated component.
239  @Entry(storage)
240  @Component
241  struct CompA {
242    // @LocalStorageProp creates a one-way data synchronization with the ProA attribute in LocalStorage.
243    @LocalStorageProp('PropA') storProp1: number = 1;
244
245    build() {
246      Column({ space: 15 }) {
247        // The initial value is 47. After the button is clicked, the value is incremented by 1. The change takes effect only in storProp1 in the current component and is not synchronized to LocalStorage.
248        Button(`Parent from LocalStorage ${this.storProp1}`)
249          .onClick(() => this.storProp1 += 1)
250        Child()
251      }
252    }
253  }
254
255  @Component
256  struct Child {
257    // @LocalStorageProp creates a one-way data synchronization with the ProA attribute in LocalStorage.
258    @LocalStorageProp('PropA') storProp2: number = 2;
259
260    build() {
261      Column({ space: 15 }) {
262        // When CompA changes, the current storProp2 does not change, and 47 is displayed.
263        Text(`Parent from LocalStorage ${this.storProp2}`)
264      }
265    }
266  }
267  ```
268
269
270### Simple Example of Using \@LocalStorageLink and LocalStorage
271
272This example shows how to create a two-way data synchronization between an \@LocalStorageLink decorated variable and LocalStorage.
273
274
275```ts
276// Create a LocalStorage instance.
277let storage = new LocalStorage({ 'PropA': 47 });
278// Invoke the link9+ API to create a two-way data synchronization with PropA. linkToPropA is a global variable.
279let linkToPropA = storage.link('PropA');
280
281@Entry(storage)
282@Component
283struct CompA {
284
285  // @LocalStorageLink('PropA') creates a two-way synchronization with PropA in the CompA custom component. The initial value is 47, because PropA has been set to 47 during LocalStorage construction.
286  @LocalStorageLink('PropA') storLink: number = 1;
287
288  build() {
289    Column() {
290      Text(`incr @LocalStorageLink variable`)
291        // Clicking incr @LocalStorageLink variable increases the value of this.storLink by 1. The change is synchronized back to the storage. The global variable linkToPropA also changes.
292
293        .onClick(() => this.storLink += 1)
294
295      // Avoid using the global variable linkToPropA.get() in the component. Doing so may cause errors due to different lifecycles.
296      Text(`@LocalStorageLink: ${this.storLink} - linkToPropA: ${linkToPropA.get()}`)
297    }
298  }
299}
300```
301
302
303### State Variable Synchronization Between Sibling Nodes
304
305This example shows how to use \@LocalStorageLink to create a two-way synchronization for the state between sibling nodes.
306
307Check the changes in the **Parent** custom component.
308
3091. Clicking **playCount ${this.playCount} dec by 1** decreases the value of **this.playCount** by 1. This change is synchronized to LocalStorage and to the components bound to **playCountLink** in the **Child** component.
310
3112. Click **countStorage ${this.playCount} incr by 1** to call the **set** API in LocalStorage to update the attributes corresponding to **countStorage** in LocalStorage. The components bound to** playCountLink** in the **Child** component are updated synchronously.
312
3133. The **playCount in LocalStorage for debug ${storage.get&lt;number&gt;('countStorage')}** **\<Text>** component is not updated synchronously, because **storage.get<number>('countStorage')** returns a regular variable. The update of a regular variable does not cause the **\<Text>** component to be re-rendered.
314
315Changes in the **Child** custom component:
316
3171. The update of **playCountLink** is synchronized to LocalStorage, and the parent and sibling child custom components are re-rendered accordingly.
318
319   ```ts
320   let storage = new LocalStorage({ countStorage: 1 });
321
322   @Component
323   struct Child {
324     // Name the child component instance.
325     label: string = 'no name';
326     // Two-way synchronization with countStorage in LocalStorage.
327     @LocalStorageLink('countStorage') playCountLink: number = 0;
328
329     build() {
330       Row() {
331         Text(this.label)
332           .width(50).height(60).fontSize(12)
333         Text(`playCountLink ${this.playCountLink}: inc by 1`)
334           .onClick(() => {
335             this.playCountLink += 1;
336           })
337           .width(200).height(60).fontSize(12)
338       }.width(300).height(60)
339     }
340   }
341
342   @Entry(storage)
343   @Component
344   struct Parent {
345     @LocalStorageLink('countStorage') playCount: number = 0;
346
347     build() {
348       Column() {
349         Row() {
350           Text('Parent')
351             .width(50).height(60).fontSize(12)
352           Text(`playCount ${this.playCount} dec by 1`)
353             .onClick(() => {
354               this.playCount -= 1;
355             })
356             .width(250).height(60).fontSize(12)
357         }.width(300).height(60)
358
359         Row() {
360           Text('LocalStorage')
361             .width(50).height(60).fontSize(12)
362           Text(`countStorage ${this.playCount} incr by 1`)
363             .onClick(() => {
364               storage.set<number>('countStorage', 1 + storage.get<number>('countStorage'));
365             })
366             .width(250).height(60).fontSize(12)
367         }.width(300).height(60)
368
369         Child({ label: 'ChildA' })
370         Child({ label: 'ChildB' })
371
372         Text(`playCount in LocalStorage for debug ${storage.get<number>('countStorage')}`)
373           .width(300).height(60).fontSize(12)
374       }
375     }
376   }
377   ```
378
379
380### Sharing a LocalStorage Instance from UIAbility to One or More Pages
381
382In the preceding examples, the LocalStorage instance is shared only in an \@Entry decorated component and its owning child component (a page). To enable a LocalStorage instance to be shared across pages, you can create a LocalStorage instance in the owning UIAbility and call windowStage.[loadContent](../reference/apis/js-apis-window.md#loadcontent9).
383
384
385```ts
386// EntryAbility.ts
387import UIAbility from '@ohos.app.ability.UIAbility';
388import window from '@ohos.window';
389
390export default class EntryAbility extends UIAbility {
391  storage: LocalStorage = new LocalStorage({
392    'PropA': 47
393  });
394
395  onWindowStageCreate(windowStage: window.WindowStage) {
396    windowStage.loadContent('pages/Index', this.storage);
397  }
398}
399```
400
401On the page, call the **GetShared** API to obtain the LocalStorage instance shared through **loadContent**.
402
403
404```ts
405// Use the GetShared API to obtain the Storage instance shared by stage.
406let storage = LocalStorage.GetShared()
407
408@Entry(storage)
409@Component
410struct CompA {
411  // can access LocalStorage instance using
412  // @LocalStorageLink/Prop decorated variables
413  @LocalStorageLink('PropA') varA: number = 1;
414
415  build() {
416    Column() {
417      Text(`${this.varA}`).fontSize(50)
418    }
419  }
420}
421```
422
423
424> **NOTE**
425>
426> It is good practice to always create a LocalStorage instance with meaningful default values, which serve as a backup when execution exceptions occur and are also useful for unit testing of pages.
427
428<!--no_check-->
429