0.0.1 • Published 7 months ago

hook-model v0.0.1

Weekly downloads
-
License
-
Repository
-
Last release
7 months ago

useModel

A flexible React hook for managing state with a proxy-based event system. This hook provides an elegant way to handle state updates and resets with a clean, intuitive API.

Features

  • Proxy-based state management
  • Individual field updates and resets
  • Full state reset capability
  • Type-safe state manipulation
  • Minimal boilerplate

Installation

npm install hook-model
# or
yarn add hook-model

Usage

import { useModel } from 'hook-model';

function UserForm() {
	const initialState = {
		name: '',
		email: '',
		age: 0
	};

	const [state, event] = useModel(initialState);

	// Using individual field handlers
	const handleNameChange = (e) => {
		event.name.set(e.target.value);
	};

	// Using direct set method
	const handleEmailChange = (e) => {
		event.set('email', e.target.value);
	};

	// Reset single field
	const resetAge = () => {
		event.age.reset();
	};

	// Reset all fields
	const resetForm = () => {
		event.reset();
	};

	return (
		<form>
			<input value={state.name} onChange={handleNameChange} />
			<input value={state.email} onChange={handleEmailChange} />
			<input value={state.age} onChange={(e) => event.age.set(Number(e.target.value))} />
			<button type="button" onClick={resetAge}>
				Reset Age
			</button>
			<button type="button" onClick={resetForm}>
				Reset Form
			</button>
		</form>
	);
}

API

useModel(initialState)

Returns a tuple containing the current state and an event handler object.

Parameters

  • initialState: Object containing the initial state values

Returns

  • [state, event]: Tuple containing:
    • state: Current state object
    • event: Proxy object with state manipulation methods

Event Handler Methods

  • event.set(key, value): Set a specific field value
  • event.reset([key]): Reset specific field or entire state
  • event[field].set(value): Set value for specific field
  • event[field].reset(): Reset specific field to initial value
0.0.1

7 months ago