• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.StateManagement (State Management)
2
3The state management module provides data storage, persistent data management, UIAbility data storage, and environment state and tools required by applications.
4
5>**NOTE**
6>
7>The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9
10The meanings of T and S in this topic are as follows:
11
12
13| Type  | Description                                    |
14| ---- | -------------------------------------- |
15| T    | Class, number, boolean, string, and arrays of these types.|
16| S    | number, boolean, string.                |
17
18
19## Modules to Import
20
21```ts
22import { AppStorageV2, PersistenceV2, UIUtils } from '@kit.ArkUI';
23```
24
25## AppStorageV2
26
27For details about how to use AppStorageV2, see [AppStorageV2: Storing Application-wide UI State](../../ui/state-management/arkts-new-appstoragev2.md).
28
29**Atomic service API**: This API can be used in atomic services since API version 12.
30
31**System capability**: SystemCapability.ArkUI.ArkUI.Full
32
33### connect
34
35static connect\<T extends object\>( <br>
36      type: TypeConstructorWithArgs\<T\>, <br>
37      keyOrDefaultCreator?: string | StorageDefaultCreator\<T\>, <br>
38      defaultCreator?: StorageDefaultCreator\<T\> <br>
39): T | undefined
40
41Stores key-value pair data in the application memory. If the given key already exists in [AppStorageV2](../../ui/state-management/arkts-new-appstoragev2.md), it returns the corresponding value; otherwise, it constructs a default value using the constructor for obtaining the default value and returns it.
42
43**Atomic service API**: This API can be used in atomic services since API version 12.
44
45**System capability**: SystemCapability.ArkUI.ArkUI.Full
46
47**Parameters**
48
49| Name  | Type  | Mandatory| Description              |
50| -------- | ------ | ---- | ---------------------- |
51| type | [TypeConstructorWithArgs\<T\>](#typeconstructorwithargst) | Yes  | Type. If no key is specified, the name of the type is used as the key.|
52| keyOrDefaultCreator | string \| [StorageDefaultCreator\<T\>](#storagedefaultcreatort) | No  | Key, or the constructor for obtaining the default value.|
53| defaultCreator | StorageDefaultCreator\<T\> | No  | Constructor for obtaining the default value.|
54
55>**NOTE**
56>
57>1. The second parameter is used when no key is specified, and the third parameter is used otherwise.
58>
59>2. If the data has been stored in AppStorageV2, you can obtain the stored data without using the default constructor. If the data has not been stored, you must specify a default constructor; otherwise, an application exception will be thrown.
60>
61>3. Ensure that the data types match the key. Connecting different types of data to the same key will result in an application exception.
62>
63>4. You are advised to use meaningful values for the key, with a length not exceeding 255 characters. The behavior of using illegal characters or empty characters is undefined.
64
65**Return value**
66
67| Type                                  | Description                                                        |
68| -------------------------------------- | ------------------------------------------------------------ |
69| T \| undefined | Returns data if the creation or data acquisition from AppStorageV2 is successful; returns **undefined** otherwise.|
70
71**Example**
72
73```ts
74import { AppStorageV2 } from '@kit.ArkUI';
75
76@ObservedV2
77class SampleClass {
78  @Trace p: number = 0;
79}
80
81// Store the key-value pair with the key SampleClass and the value as a new instance of SampleClass() in memory, and assign it to variable as1.
82const as1: SampleClass | undefined = AppStorageV2.connect(SampleClass, () => new SampleClass());
83
84// Store the key-value pair with the key key_as2 and the value as a new instance of SampleClass() in memory, and assign it to variable as2.
85const as2: SampleClass = AppStorageV2.connect(SampleClass, 'key_as2', () => new SampleClass())!;
86
87// As the key SampleClass already exists in AppStorageV2, the value associated with the key is returned to variable as3.
88const as3: SampleClass = AppStorageV2.connect(SampleClass) as SampleClass;
89```
90
91### remove
92
93static remove\<T\>(keyOrType: string | TypeConstructorWithArgs\<T\>): void
94
95Removes the specified key-value pair from [AppStorageV2](../../ui/state-management/arkts-new-appstoragev2.md). If the specified key does not exist in AppStorageV2, the removal will fail.
96
97**Atomic service API**: This API can be used in atomic services since API version 12.
98
99**System capability**: SystemCapability.ArkUI.ArkUI.Full
100
101**Parameters**
102
103| Name  | Type  | Mandatory| Description              |
104| -------- | ------ | ---- | ---------------------- |
105| keyOrType | string \| TypeConstructorWithArgs\<T\> | Yes  | Key to be removed. If a type is specified, the key to be deleted is the name of that type.|
106
107>**NOTE**
108>
109>Attempting to remove a key that does not exist in AppStorageV2 will result in a warning.
110
111
112**Example**
113
114<!--code_no_check-->
115```ts
116// Assuming that there is a key named key_as2 in AppStorageV2, the following will remove the corresponding key-value pair from AppStorageV2.
117AppStorageV2.remove('key_as2');
118
119// Assuming that there is a key named SampleClass in AppStorageV2, the following will remove the corresponding key-value pair from AppStorageV2.
120AppStorageV2.remove(SampleClass);
121
122// Assuming there is no key named key_as1 in AppStorageV2, the following will result in a warning.
123AppStorageV2.remove('key_as1');
124```
125
126### keys
127
128static keys(): Array\<string\>
129
130Obtains all keys in [AppStorageV2](../../ui/state-management/arkts-new-appstoragev2.md).
131
132**Atomic service API**: This API can be used in atomic services since API version 12.
133
134**System capability**: SystemCapability.ArkUI.ArkUI.Full
135
136**Return value**
137
138| Type                                  | Description                                                        |
139| -------------------------------------- | ------------------------------------------------------------ |
140| Array\<string\> | All keys stored in AppStorageV2.|
141
142>**NOTE**
143>
144>The order of the keys in the Array is not sequential and does not correspond to the order in which the keys were inserted into AppStorageV2.
145
146**Example**
147
148```ts
149// Assuming there are two keys (key_as1 and key_as2) in AppStorageV2, the following will return an array containing these keys and assign it to keys.
150const keys: Array<string> = AppStorageV2.keys();
151```
152
153
154
155## PersistenceV2
156
157Inherits from [AppStorageV2](#appstoragev2). For details, see [PersistenceV2: Persisting Application State](../../ui/state-management/arkts-new-persistencev2.md).
158
159**Atomic service API**: This API can be used in atomic services since API version 12.
160
161**System capability**: SystemCapability.ArkUI.ArkUI.Full
162
163### globalConnect<sup>18+</sup>
164
165static globalConnect\<T extends object\>(type: ConnectOptions\<T\>): T | undefined
166
167Stores key-value pair data on the application disk. If the given key already exists in [PersistenceV2](../../ui/state-management/arkts-new-persistencev2.md), the corresponding value is returned. Otherwise, a default value is constructed using the default value constructor and returned. If **globalConnect** is used for an @ObservedV2 decorated object, changes to the object's @Trace properties will trigger automatic refresh of the associated object, while changes to non-@Trace properties will not. If necessary, the **PersistenceV2.save** API can be called to store the data manually.
168
169**Atomic service API**: This API can be used in atomic services since API version 18.
170
171**System capability**: SystemCapability.ArkUI.ArkUI.Full
172
173| Name  |Type  |Mandatory  | Description                                                     |
174| ------------- | ------------|-------------------|-------------------------- |
175| type    |[ConnectOptions\<T\>](#connectoptions18)    |Yes |**connect** parameter passed in. For details, see the description of **ConnectOptions**.|
176
177**Return value**
178
179|Type  |Description                |
180|----------|-----------------------------------|
181|T \| undefined    |Returns the data if creation or acquisition is successful; otherwise, returns **undefined**.   |
182
183> **NOTE**
184>
185> 1. The second parameter is used when no **key** is specified, and the third parameter is used otherwise (including when the second parameter is invalid).
186>
187> 2. If the data has been stored in PersistenceV2, you can obtain the stored data without using the default constructor. Otherwise, you must specify a default constructor to avoid application exceptions.
188>
189> 3. Ensure that the data types match the key. Matching different types of **globalConnect** data to the same key will result in an application exception.
190>
191> 4. You are advised to use meaningful values for keys. The values can contain letters, digits, and underscores (_) and a maximum of 255 characters. Using invalid characters or null characters will result in undefined behavior.
192>
193> 5. When matching the key with an [\@Observed](../../ui/state-management/arkts-observed-and-objectlink.md) object, specify the key or customize the **name** property.
194>
195> 6. The storage path for data is application-level. If different modules use the same key and the same encryption partition for **globalConnect**, only one copy of the data will be stored in the application.
196>
197> 7. If **globalConnect** is used with the same key but different encryption levels, the data will be stored with the encryption level of the first **globalConnect** call, and the data in **PersistenceV2** will also be stored with this encryption level.
198>
199> 8. Avoid using **connect** and **globalConnect** together, because they have different data copy paths. If they must be used together, make sure the keys are unique to avoid application crashes.
200>
201> 9. To enable EL5 encryption, configure the **ohos.permission.PROTECT_SCREEN_LOCK_DATA** field in the **module.json** file. For details, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md).
202
203**Example**
204This example is provided for you to understand the usage of **globalConnect**. You need to write your own @Entry component for complete usage.
205
206<!--code_no_check-->
207```ts
208import { PersistenceV2, Type, ConnectOptions } from '@kit.ArkUI';
209import { contextConstant } from '@kit.AbilityKit';
210
211@ObservedV2
212class SampleChild {
213  @Trace childId: number = 0;
214  groupId: number = 1;
215}
216
217@ObservedV2
218export class Sample {
219  // For complex objects, use the @Type decorator to ensure successful serialization.
220  @Type(SampleChild)
221  @Trace father: SampleChild = new SampleChild();
222}
223
224// If no key is provided, the type name is used as the key. If the encryption level is not specified, the default EL2 level is used.
225const p: Sample = PersistenceV2.globalConnect({ type: Sample, defaultCreator: () => new Sample() })!;
226
227// Use the key 'global1' with an encryption level of EL1 for connection.
228const p1: Sample = PersistenceV2.globalConnect({
229  type: Sample,
230  key: 'global1',
231  defaultCreator: () => new Sample(),
232  areaMode: contextConstant.AreaMode.EL1
233})!;
234
235// Use the key 'global2' with the constructor function for connection. If no encryption level is specified, the default EL2 level is used.
236const p2: Sample = PersistenceV2.globalConnect({ type: Sample, key: 'global2', defaultCreator: () => new Sample() })!;
237
238// Use the key 'global3' with an explicit encryption level value (3 in this example) for connection. Note that values outside the valid range of 0-4 will cause application crashes.
239const p3: Sample = PersistenceV2.globalConnect({
240  type: Sample,
241  key: 'global3',
242  defaultCreator: () => new Sample(),
243  areaMode: 3
244})!;
245
246```
247
248### save
249
250static save\<T\>(keyOrType: string | TypeConstructorWithArgs\<T\>): void
251
252Persists the specified key-value pair data once.
253
254**Atomic service API**: This API can be used in atomic services since API version 12.
255
256**System capability**: SystemCapability.ArkUI.ArkUI.Full
257
258**Parameters**
259
260| Name  | Type  | Mandatory| Description              |
261| -------- | ------ | ---- | ---------------------- |
262| keyOrType | string \| TypeConstructorWithArgs\<T\> | Yes  | Key to be persisted. If a type is specified, the key for persistence is the name of the type.|
263
264>**NOTE**
265>
266>Since changes to non-[\@Trace](../../ui/state-management/arkts-new-observedV2-and-trace.md) decorated data do not automatically trigger persistence through [PersistenceV2](../../ui/state-management/arkts-new-persistencev2.md), you can call this API to manually persist the data for the corresponding key when needed.
267>
268>It is useless to manually persist the keys that are not in the **connect** state in the memory.
269
270**Example**
271
272<!--code_no_check-->
273
274```ts
275@ObservedV2
276class SampleClass {
277  @Trace p: number = 0;
278}
279
280// Assuming there is a key named key_as2 in PersistenceV2, the following will persist the data for this key-value pair.
281PersistenceV2.save('key_as2');
282
283// Assuming there is a key named SampleClass in PersistenceV2, the following will persist the data for this key-value pair.
284PersistenceV2.save(SampleClass);
285
286// Assuming there is no key named key_as1 in PersistenceV2, this operation is meaningless.
287PersistenceV2.save('key_as1');
288```
289
290### notifyOnError
291
292static notifyOnError(callback: PersistenceErrorCallback | undefined): void
293
294Called when persistence fails.
295
296**Atomic service API**: This API can be used in atomic services since API version 12.
297
298**System capability**: SystemCapability.ArkUI.ArkUI.Full
299
300**Parameters**
301
302| Name  | Type  | Mandatory| Description              |
303| -------- | ------ | ---- | ---------------------- |
304| callback | PersistenceErrorCallback \| undefined  | Yes  | Callback invoked when persistence fails.|
305
306**Example**
307
308```ts
309// Called when persistence fails.
310PersistenceV2.notifyOnError((key: string, reason: string, msg: string) => {
311  console.error(`error key: ${key}, reason: ${reason}, message: ${msg}`);
312});
313```
314
315## ConnectOptions<sup>18+</sup>
316
317Defines the parameter type for **globalConnect**.
318
319**Atomic service API**: This API can be used in atomic services since API version 18.
320
321**System capability**: SystemCapability.ArkUI.ArkUI.Full
322
323|Name  |Type   |Read-Only  |Optional   |Description     |
324|--------|------------|------------|-----------|--------------|
325|type        | TypeConstructorWithArgs\<T\>   |No  |No  |Specified type.        |
326|key         | string   |No  |Yes  |key used for connection. If it is not provided, the name of the type is used as the key.            |
327|defaultCreator   | StorageDefaultCreator\<T\>   |No  |Yes  |Default constructor. It is recommended that this parameter be passed in. If **globalConnect** is called for the first time with a key and this parameter is not provided, an error will occur.|
328|areaMode      | contextConstant.AreaMode   |No  |Yes   |Encryption level, ranging from EL1 to EL5 (corresponding to the value from 0 to 4). For details, see [Encryption Levels](../../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). If no value is passed in, EL2 is used by default. Storage paths vary based on the encryption levels. If the input value of encryption level is not in the range of **0** to **4**, a crash occurs.|
329
330## UIUtils
331
332Provides APIs for handling data transformations related to state management.
333
334**Atomic service API**: This API can be used in atomic services since API version 12.
335
336**System capability**: SystemCapability.ArkUI.ArkUI.Full
337
338### getTarget
339
340static getTarget\<T extends object\>(source: T): T
341
342Obtains the original object from a proxy object wrapped by the state management framework. For details, see [getTarget API: Obtaining Original Objects](../../ui/state-management/arkts-new-getTarget.md).
343
344**Atomic service API**: This API can be used in atomic services since API version 12.
345
346**System capability**: SystemCapability.ArkUI.ArkUI.Full
347
348**Parameters**
349
350| Name| Type| Mandatory| Description    |
351| ------ | ---- | ---- | ------------ |
352| source | T    | Yes  | Source object.|
353
354**Return value**
355
356| Type| Description                                            |
357| ---- | ------------------------------------------------ |
358| T    | Original object of the source after the proxy added by the state management framework is removed.|
359
360**Example**
361
362```ts
363import { UIUtils } from '@kit.ArkUI';
364class NonObservedClass {
365  name: string = "Tom";
366}
367let nonObservedClass: NonObservedClass = new NonObservedClass();
368@Entry
369@Component
370struct Index {
371  @State someClass: NonObservedClass = nonObservedClass;
372  build() {
373    Column() {
374      Text(`this.someClass === nonObservedClass: ${this.someClass === nonObservedClass}`) // false
375      Text(`UIUtils.getTarget(this.someClass) === nonObservedClass: ${UIUtils.getTarget(this.someClass) ===
376        nonObservedClass}`) // true
377    }
378  }
379}
380```
381### makeObserved
382
383static makeObserved\<T extends object\>(source: T): T
384
385Converts ordinary unobservable data into observable data. For details, see [makeObserved API: Changing Unobservable Data to Observable Data](../../ui/state-management/arkts-new-makeObserved.md).
386
387**Atomic service API**: This API can be used in atomic services since API version 12.
388
389**System capability**: SystemCapability.ArkUI.ArkUI.Full
390
391**Parameters**
392
393| Name| Type| Mandatory| Description    |
394| ------ | ---- | ---- | ------------ |
395| source | T    | Yes  | Source object. It supports classes not decorated by @Observed or @ObserveV2, objects returned by **JSON.parse**, and classes decorated by @Sendable.<br>Array, Map, Set, and Date types are supported.<br>**collection.Array**, **collection.Set**, and **collection.Map** are supported.<br>For details, see [makeObserved API: Changing Unobservable Data to Observable Data](../../ui/state-management/arkts-new-makeObserved.md).|
396
397**Return value**
398
399| Type| Description                                            |
400| ---- | ------------------------------------------------ |
401| T    | Observable data.|
402
403**Example**
404
405```ts
406import { UIUtils } from '@kit.ArkUI';
407class NonObservedClass {
408  name: string = 'Tom';
409}
410
411@Entry
412@ComponentV2
413struct Index {
414  observedClass: NonObservedClass = UIUtils.makeObserved(new NonObservedClass());
415  nonObservedClass: NonObservedClass = new NonObservedClass();
416  build() {
417    Column() {
418      Text(`observedClass: ${this.observedClass.name}`)
419        .onClick(() => {
420          this.observedClass.name = 'Jane'; // This will trigger a UI update.
421        })
422      Text(`observedClass: ${this.nonObservedClass.name}`)
423        .onClick(() => {
424          this.nonObservedClass.name = 'Jane'; // This will not trigger a UI update.
425        })
426    }
427  }
428}
429```
430
431### enableV2Compatibility<sup>19+</sup>
432
433static enableV2Compatibility\<T extends object\>(source: T): T
434
435Enables V1 state variables to be observable in @ComponentV2. This API is primarily used in scenarios where V1 and V2 state management are mixed. For details, see [Mixing Use of State Management V1 and V2](../../ui/state-management/arkts-v1-v2-mixusage.md).
436
437**Atomic service API**: This API can be used in atomic services since API version 19.
438
439**System capability**: SystemCapability.ArkUI.ArkUI.Full
440
441**Parameters**
442
443| Name| Type| Mandatory| Description    |
444| ------ | ---- | ---- | ------------ |
445| source | T    | Yes  | Data source, which must be V1 state data.|
446
447**Return value**
448
449| Type| Description                                            |
450| ---- | ------------------------------------------------ |
451| T    | If the data source is V1 state data, returns data that can be observed in @ComponentV2; otherwise, returns the data source itself.|
452
453
454**Example**
455
456```ts
457import { UIUtils } from '@kit.ArkUI';
458
459@Observed
460class ObservedClass {
461  name: string = 'Tom';
462}
463
464@Entry
465@Component
466struct CompV1 {
467  @State observedClass: ObservedClass = new ObservedClass();
468
469  build() {
470    Column() {
471      Text(`@State observedClass: ${this.observedClass.name}`)
472        .onClick(() => {
473          this.observedClass.name = 'State'; // Refresh
474        })
475      // Enable V2 observability for the V1 state variable.
476      CompV2({ observedClass: UIUtils.enableV2Compatibility(this.observedClass) })
477    }
478  }
479}
480
481@ComponentV2
482struct CompV2 {
483  @Param observedClass: ObservedClass = new ObservedClass();
484
485  build() {
486    // After V2 observability is enabled for the V1 state variable, the first-layer changes can be observed in V2.
487    Text(`@Param observedClass: ${this.observedClass.name}`)
488      .onClick(() => {
489        this.observedClass.name = 'Param'; // Refresh
490      })
491  }
492}
493```
494
495### makeV1Observed<sup>19+</sup>
496static makeV1Observed\<T extends object\>(source: T): T
497
498Wraps an unobservable object into an object that is observable by V1 state management. This API is equivalent to @Observed and can be used to initialize @ObjectLink.
499
500This API can be used in conjunction with [enableV2Compatibility](#enablev2compatibility19) for scenarios where V1 and V2 state management are mixed. For details, see [Mixing Use of State Management V1 and V2](../../ui/state-management/arkts-v1-v2-mixusage.md).
501
502**Atomic service API**: This API can be used in atomic services since API version 19.
503
504**System capability**: SystemCapability.ArkUI.ArkUI.Full
505
506**Parameters**
507
508| Name| Type| Mandatory| Description    |
509| ------ | ---- | ---- | ------------ |
510| source | T    | Yes  | Data source. Common class, Array, Map, Set, and Date types are supported.<br>The [collections](../apis-arkts/js-apis-arkts-collections.md) type and [\@Sendable](../../arkts-utils/arkts-sendable.md) decorated classes are not supported.<br>**undefined** and **null** are not supported. V2 state management data and the return value of [makeObserved](#makeobserved) are not supported.|
511
512**Return value**
513
514| Type| Description                                            |
515| ---- | ------------------------------------------------ |
516| T    | For supported input parameter types, returns data observable by V1 state management. For unsupported input parameter types, returns the data source object itself.|
517
518**Example**
519
520```ts
521import { UIUtils } from '@kit.ArkUI';
522
523class Outer {
524  outerValue: string = 'outer';
525  inner: Inner;
526
527  constructor(inner: Inner) {
528    this.inner = inner;
529  }
530}
531
532class Inner {
533  interValue: string = 'inner';
534}
535
536@Entry
537@Component
538struct Index {
539  @State outer: Outer = new Outer(UIUtils.makeV1Observed(new Inner()));
540
541  build() {
542    Column() {
543      // The return value of makeV1Observed can be used to initialize @ObjectLink.
544      Child({ inner: this.outer.inner })
545    }
546    .height('100%')
547    .width('100%')
548  }
549}
550
551@Component
552struct Child {
553  @ObjectLink inner: Inner;
554
555  build() {
556    Text(`${this.inner.interValue}`)
557      .onClick(() => {
558        this.inner.interValue += '!';
559      })
560  }
561}
562```
563
564## StorageDefaultCreator\<T\>
565
566type StorageDefaultCreator\<T\> = () => T
567
568Obtains the default constructor.
569
570**Atomic service API**: This API can be used in atomic services since API version 12.
571
572**System capability**: SystemCapability.ArkUI.ArkUI.Full
573
574**Return value**
575
576| Type| Description                                            |
577| ---- | ------------------------------------------------ |
578| () => T    | Default constructor.|
579
580**Example**
581
582```ts
583import { PersistenceV2 } from '@kit.ArkUI';
584
585@ObservedV2
586class SampleClass {
587  @Trace id: number = 0;
588  count: number = 1;
589}
590
591@ObservedV2
592class FatherSampleClass {
593  @Trace sampleClass: SampleClass = new SampleClass();
594}
595
596// Persist the key-value pair with the key SampleClass and the value as an instance of SampleClass(), and assign it to variable source.
597// StorageDefaultCreator refers to the function () => new FatherSampleClass().
598const source: FatherSampleClass | undefined = PersistenceV2.connect(FatherSampleClass, () => new FatherSampleClass());
599
600@Entry
601@Component
602struct SampleComp {
603  data: FatherSampleClass | undefined = source;
604
605  build() {
606    Column() {
607      Text(`${this.data?.sampleClass.id}`)
608    }
609  }
610}
611```
612
613## TypeConstructorWithArgs\<T\>
614
615Represents a class constructor that accepts arbitrary arguments.
616
617**Atomic service API**: This API can be used in atomic services since API version 12.
618
619**System capability**: SystemCapability.ArkUI.ArkUI.Full
620
621### new
622
623new(...args: any): T
624
625Creates and returns an instance of the specified type T.
626
627**Atomic service API**: This API can be used in atomic services since API version 12.
628
629**System capability**: SystemCapability.ArkUI.ArkUI.Full
630
631**Parameters**
632
633| Name| Type| Mandatory| Description    |
634| ------ | ---- | ---- | ------------ |
635| ...args | any    | Yes  | Function arguments.  |
636
637**Return value**
638
639| Type| Description                                            |
640| ---- | ------------------------------------------------ |
641| T    | Instance of the T type.|
642
643**Example**
644
645```ts
646import { PersistenceV2 } from '@kit.ArkUI';
647
648@ObservedV2
649  // TypeConstructorWithArgs refers to the SampleClass constructor.
650class SampleClass {
651  @Trace id: number = 0;
652  count: number = 1;
653}
654
655@ObservedV2
656class FatherSampleClass {
657  @Trace sampleClass: SampleClass = new SampleClass();
658}
659
660// Persist the key-value pair with the key SampleClass and the value as an instance of SampleClass(), and assign it to variable source.
661const source: FatherSampleClass | undefined = PersistenceV2.connect(FatherSampleClass, () => new FatherSampleClass());
662
663@Entry
664@Component
665struct SampleComp {
666  data: FatherSampleClass | undefined = source;
667
668  build() {
669    Column() {
670      Text(`${this.data?.sampleClass.id}`)
671    }
672  }
673}
674```
675
676## PersistenceErrorCallback
677
678type PersistenceErrorCallback = (key: string, reason: 'quota' | 'serialization' | 'unknown', message: string) => void
679
680Represents the callback invoked when persistence fails.
681
682**Atomic service API**: This API can be used in atomic services since API version 12.
683
684**System capability**: SystemCapability.ArkUI.ArkUI.Full
685
686**Parameters**
687
688| Name| Type| Mandatory| Description    |
689| ------ | ---- | ---- | ------------ |
690| key | string    | Yes  | Key associated with the error.  |
691|reason| 'quota' \| 'serialization' \| 'unknown'    | Yes  | Type of the error.  |
692| message | string    | Yes  | Additional information about the error.  |
693
694**Example**
695
696```ts
697import { PersistenceV2, Type } from '@kit.ArkUI';
698
699@ObservedV2
700class SampleChild {
701  @Trace id: number = 0;
702  count: number = 10;
703}
704
705@ObservedV2
706export class Sample {
707  // For complex objects, use the @Type decorator to ensure successful serialization.
708  @Type(SampleChild)
709  @Trace sampleChild: SampleChild = new SampleChild();
710}
711
712// Callback used to receive persistence errors.
713// PersistenceErrorCallback refers to (key: string, reason: string, msg: string) => {console.error(`error key: ${key}, reason: ${reason}, message: ${msg}`);}.
714PersistenceV2.notifyOnError((key: string, reason: string, msg: string) => {
715  console.error(`error key: ${key}, reason: ${reason}, message: ${msg}`);
716});
717
718@Entry
719@ComponentV2
720struct Index {
721  // Create a key-value pair with the key Sample in PersistenceV2 (if the key exists, the data in PersistenceV2 is returned) and associate it with data.
722  // Add @Local to decorate the data property that needs to change the connected object. (Changing the connected object is not recommended.)
723  @Local data: Sample = PersistenceV2.connect(Sample, () => new Sample())!;
724  pageStack: NavPathStack = new NavPathStack();
725
726  build() {
727    Text(`Index add 1 to data.id: ${this.data.sampleChild.id}`)
728      .fontSize(30)
729      .onClick(() => {
730        this.data.sampleChild.id++;
731      })
732  }
733}
734```
735
736## TypeConstructor\<T\>
737
738Class constructor.
739
740**Atomic service API**: This API can be used in atomic services since API version 12.
741
742**System capability**: SystemCapability.ArkUI.ArkUI.Full
743
744### new
745
746new(): T
747
748Creates and returns an instance of the specified type T.
749
750**Atomic service API**: This API can be used in atomic services since API version 12.
751
752**System capability**: SystemCapability.ArkUI.ArkUI.Full
753
754**Return value**
755
756| Type| Description                                            |
757| ---- | ------------------------------------------------ |
758| T    | Instance of the T type.|
759
760**Example**
761
762```ts
763import { PersistenceV2, Type } from '@kit.ArkUI';
764
765@ObservedV2
766class SampleChild {
767  @Trace id: number = 0;
768  count: number = 10;
769}
770
771@ObservedV2
772export class Sample {
773  // For complex objects, use the @Type decorator to ensure successful serialization.
774  // TypeConstructor refers to SampleChild.
775  @Type(SampleChild)
776  @Trace sampleChild: SampleChild = new SampleChild();
777}
778
779@Entry
780@ComponentV2
781struct Index {
782  data: Sample = PersistenceV2.connect(Sample, () => new Sample())!;
783
784  build() {
785    Column() {
786      Text(`Index add 1 to data.id: ${this.data.sampleChild.id}`)
787        .fontSize(30)
788        .onClick(() => {
789          this.data.sampleChild.id++;
790        })
791    }
792  }
793}
794```
795
796## TypeDecorator
797
798type TypeDecorator = \<T\>(type: TypeConstructor\<T\>) => PropertyDecorator
799
800Property decorator.
801
802**Atomic service API**: This API can be used in atomic services since API version 12.
803
804**System capability**: SystemCapability.ArkUI.ArkUI.Full
805
806**Parameters**
807
808| Name| Type| Mandatory| Description    |
809| ------ | ---- | ---- | ------------ |
810| type | [TypeConstructor\<T\>](#typeconstructort)    | Yes  | Type of the class property decorated.  |
811
812**Return value**
813
814| Type| Description                                            |
815| ---- | ------------------------------------------------ |
816| PropertyDecorator    | Property decorator.|
817
818**Example**
819
820```ts
821import { PersistenceV2, Type } from '@kit.ArkUI';
822
823@ObservedV2
824class SampleChild {
825  @Trace id: number = 0;
826  count: number = 10;
827}
828
829@ObservedV2
830export class Sample {
831  // For complex objects, use the @Type decorator to ensure successful serialization.
832  // TypeDecorator refers to @Type.
833  @Type(SampleChild)
834  @Trace sampleChild: SampleChild = new SampleChild();
835}
836
837@Entry
838@ComponentV2
839struct Index {
840  data: Sample = PersistenceV2.connect(Sample, () => new Sample())!;
841
842  build() {
843    Column() {
844      Text(`Index add 1 to data.id: ${this.data.sampleChild.id}`)
845        .fontSize(30)
846        .onClick(() => {
847          this.data.sampleChild.id++;
848        })
849    }
850  }
851}
852```
853