@@ -22,6 +22,7 @@ import type {
2222 EventTypeName ,
2323 IStorage ,
2424 RecordOptions ,
25+ UseStateOptions ,
2526} from '@crawlee/core' ;
2627import {
2728 Configuration as CoreConfiguration ,
@@ -823,6 +824,41 @@ export class Actor<Data extends Dictionary = Dictionary> {
823824 return ! ! process . env [ ENV_VARS . IS_AT_HOME ] ;
824825 }
825826
827+ /**
828+ * Easily create and manage state values. All state values are automatically persisted.
829+ *
830+ * Values can be modified by simply using the assignment operator.
831+ *
832+ * @param name The name of the store to use.
833+ * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
834+ * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
835+ */
836+ async useState < State extends Dictionary = Dictionary > (
837+ name ?: string ,
838+ defaultValue = { } as State ,
839+ options ?: UseStateOptions ,
840+ ) {
841+ const kvStore = await KeyValueStore . open ( options ?. keyValueStoreName , { config : options ?. config || Configuration . getGlobalConfig ( ) } ) ;
842+ return kvStore . getAutoSavedValue < State > ( name || 'APIFY_GLOBAL_STATE' , defaultValue ) ;
843+ }
844+
845+ /**
846+ * Easily create and manage state values. All state values are automatically persisted.
847+ *
848+ * Values can be modified by simply using the assignment operator.
849+ *
850+ * @param name The name of the store to use.
851+ * @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
852+ * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
853+ */
854+ static async useState < State extends Dictionary = Dictionary > (
855+ name ?: string ,
856+ defaultValue = { } as State ,
857+ options ?: UseStateOptions ,
858+ ) {
859+ return Actor . getDefaultInstance ( ) . useState < State > ( name , defaultValue , options ) ;
860+ }
861+
826862 /**
827863 * Runs the main user function that performs the job of the actor
828864 * and terminates the process when the user function finishes.
0 commit comments