add browser session id to workflow run form (#2686)
This commit is contained in:
20
skyvern-frontend/src/hooks/useLocalStorageFormDefault.ts
Normal file
20
skyvern-frontend/src/hooks/useLocalStorageFormDefault.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Returns a value from localStorage for the given key, or a fallback if not present.
|
||||
* Use this hook to initialize form default values from localStorage in a type-safe way.
|
||||
*
|
||||
* @param storageKey - The localStorage key to read
|
||||
* @param fallback - The fallback value if localStorage is empty or unavailable
|
||||
* @returns The value from localStorage (if present), otherwise the fallback
|
||||
*/
|
||||
import { useMemo } from "react";
|
||||
|
||||
export function useLocalStorageFormDefault(
|
||||
storageKey: string,
|
||||
fallback: string | null | undefined,
|
||||
): string | null | undefined {
|
||||
return useMemo(() => {
|
||||
if (typeof window === "undefined") return fallback ?? null;
|
||||
const value = localStorage.getItem(storageKey);
|
||||
return value !== null ? value : fallback ?? null;
|
||||
}, [storageKey, fallback]);
|
||||
}
|
||||
23
skyvern-frontend/src/hooks/useSyncFormFieldToStorage.ts
Normal file
23
skyvern-frontend/src/hooks/useSyncFormFieldToStorage.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useEffect } from "react";
|
||||
import { UseFormReturn, FieldValues, WatchObserver } from "react-hook-form";
|
||||
|
||||
/**
|
||||
* Syncs a form field value to localStorage whenever it changes.
|
||||
* @param form - A react-hook-form object with a .watch method
|
||||
* @param fieldName - The name of the field to watch
|
||||
* @param storageKey - The key to write to in localStorage
|
||||
*/
|
||||
export function useSyncFormFieldToStorage<T extends FieldValues>(
|
||||
form: UseFormReturn<T>,
|
||||
fieldName: keyof T & string,
|
||||
storageKey: string,
|
||||
) {
|
||||
useEffect(() => {
|
||||
const subscription = form.watch(((value, { name }) => {
|
||||
if (name === fieldName && typeof value[fieldName] === "string") {
|
||||
localStorage.setItem(storageKey, value[fieldName] as string);
|
||||
}
|
||||
}) as WatchObserver<T>);
|
||||
return () => subscription.unsubscribe();
|
||||
}, [form, fieldName, storageKey]);
|
||||
}
|
||||
Reference in New Issue
Block a user