Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add global useState helper #1551

Merged
merged 16 commits into from Sep 21, 2022
16 changes: 15 additions & 1 deletion packages/core/src/storages/utils.ts
@@ -1,5 +1,6 @@
import type { StorageClient } from '@crawlee/types';
import type { Dictionary, StorageClient } from '@crawlee/types';
import { Configuration } from '../configuration';
import { KeyValueStore } from './key_value_store';

/**
* Cleans up the local storage folder (defaults to `./storage`) created when running code locally.
Expand All @@ -22,3 +23,16 @@ export async function purgeDefaultStorages(config = Configuration.getGlobalConfi
await client.purge?.();
}
}

/**
* Easily create and manage state values. All state values are automatically persisted.
*
* Values can be modified by simply using the assignment operator.
*
* @param name The name of the store to use.
* @param defaultValue If the store does not yet have a value in it, the value will be initialized with the `defaultValue` you provide.
*/
export async function useState<T extends Dictionary = Dictionary>(name: string, defaultValue = {} as T) {
const kvStore = await KeyValueStore.open(null, { config: Configuration.getGlobalConfig() });
mstephen19 marked this conversation as resolved.
Show resolved Hide resolved
return kvStore.getAutoSavedValue<T>(name, defaultValue);
}