Appearance
Function: useSetState()
ts
function useSetState(): {
<T> (key: string, value: T | (state: State) => T | Promise<T>): Promise<void>;
(newValues: Record<string, any> | Partial<State>): Promise<void>;
};Defined in: src/UI/hooks/useSetState.ts:62
Hook that provides state update functionality with async support. Handles both static values and async/sync functions that receive current state.
Returns
Function to update state values (single key-value, batch object, or async functions)
ts
<T>(key: string, value: T | (state: State) => T | Promise<T>): Promise<void>;Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
key | string |
value | T | (state: State) => T | Promise<T> |
Returns
Promise<void>
ts
(newValues: Record<string, any> | Partial<State>): Promise<void>;Parameters
| Parameter | Type |
|---|---|
newValues | Record<string, any> | Partial<State> |
Returns
Promise<void>
Example
tsx
function MyComponent() {
const setState = useSetState();
const {userName, count, loading} = useGetState({
userName: (state) => state.user?.name || 'Guest',
count: (state) => state.items?.length || 0,
loading: (state) => state.loading || false,
});
const handleStaticUpdate = () => {
// Static value update
setState('user', { name: 'John Doe', id: 123 });
};
const handleAsyncUpdate = async () => {
// Async function update
await setState('user', async (currentState) => {
const userData = await fetchUser(currentState.selectedUserId);
return userData;
});
};
const handleBatchUpdate = () => {
// Batch update with mixed static and async
setState({
loading: true,
user: async (state) => await fetchUser(state.userId),
items: [1, 2, 3, 4, 5],
lastUpdated: new Date().toISOString(),
});
};
const handleSyncFunction = () => {
// Sync function update
setState('count', (state) => (state.items?.length || 0) + 1);
};
return (
<div>
<h1>Hello, {userName}!</h1>
<p>You have {count} items</p>
{loading && <p>Loading...</p>}
<button onClick={handleStaticUpdate}>Static Update</button>
<button onClick={handleAsyncUpdate}>Async Update</button>
<button onClick={handleBatchUpdate}>Batch Update</button>
<button onClick={handleSyncFunction}>Increment Count</button>
</div>
);
}