am-redux-state
v0.3.9
Published
مكتبة hook لدمج حالة Redux مع localStorage مع دعم debounce/throttle والتحقق من الصحة.
Maintainers
Readme
AM_ReduxState Library
AM_ReduxState is a React hook library built with Redux Toolkit designed to simplify state management by synchronizing state between Redux and localStorage. It provides built-in support for debounce and throttle to prevent excessive update calls, along with customizable validation functions for robust state control.
Table of Contents
- Overview
- Features
- Installation
- Usage
- API Documentation
- Validation Example
- FAQ
- Contributing
- Roadmap
- License
- Copyright
Overview
AM_ReduxState allows you to manage state in your React applications with ease by:
- Synchronizing state from Redux and localStorage.
- Supporting debounce and throttle for optimized performance.
- Providing auto-completion through TypeScript and detailed inline documentation.
- Allowing custom validation functions to ensure state consistency.
Features
Smart State Synchronization:
Prioritizes Redux state, then falls back to localStorage, and finally uses the initial value.Debounce/Throttle Support:
Reduces repetitive update calls with configurable delay time.Custom Validation:
Supports an array of user-defined validation functions for ensuring data integrity.Automatic Cleanup:
Automatically removes corrupted entries from localStorage to maintain reliable data.Enhanced Developer Experience:
Fully typed with TypeScript for robust auto-completion and inline documentation.
Installation
Install the library using either npm or yarn:
# Using npm
npm install am-redux-state
# Using yarn
yarn add am-redux-state
# Usage
## Basic Example
Below is a simple usage example in a React component:
```tsx
import React from 'react';
import { AM_ReduxState } from 'am-redux-state';
const ExampleComponent: React.FC = () => {
// Using the hook with full TypeScript support for auto-completion
const [data, setData, resetData, loading, error, clearLocal, clearRedux] =
AM_ReduxState<{ name: string }>("data", { name: "mohmed" });
return (
<div>
<h1>AM_ReduxState Usage Example</h1>
<p>Current Name: {data.name}</p>
{loading && <p>Loading update...</p>}
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
<button onClick={() => setData({ name: "Ahmed" }, true)}>
Update Name and Save to localStorage
</button>
<button onClick={resetData}>
Reset to Initial Value
</button>
<button onClick={clearLocal}>
Clear localStorage Data
</button>
<button onClick={clearRedux}>
Clear Redux State
</button>
</div>
);
};
export default ExampleComponent;
# Advanced Usage
You can further customize the hook behavior by:
- **Adjusting the debounceTime parameter.**
- **Passing an array of custom validation functions.**
- **Switching to throttle by setting useThrottle to true.**
For instance:
```tsx
const isNotEmpty = (value: { name: string }): boolean => {
return value.name.trim().length > 0;
};
const [data, setData] = AM_ReduxState<{ name: string }>(
"userData",
{ name: "mohmed" },
500, // Custom debounce time
[isNotEmpty], // Custom validation function(s)
false // Use debounce (set to true to use throttle)
);
/**
* AM_ReduxState Hook.
*
* @template T - The type of the managed value.
* @param key - A unique key for the state.
* @param initialValue - The initial state value.
* @param debounceTime - The debounce/throttle delay in milliseconds (default is 300).
* @param validate - Optional array of validation functions.
* @param useThrottle - Whether to use throttle instead of debounce (default is false).
* @returns {UseReduxStateReturn<T>} An array containing:
* 1. Current Value: Determined from Redux, localStorage, or the initial value.
* 2. setValue: Function to update the state value (debounced/throttled).
* 3. resetValue: Function to reset the state to its initial value.
* 4. loading: Boolean indicating the loading state during updates.
* 5. error: Error message if an error occurs.
* 6. clearLocalStorage: Function to clear the value from localStorage.
* 7. clearReduxState: Function to clear the value from Redux.
*/
export type UseReduxStateReturn<T> = [
T,
(newValue: T | ((prevValue: T) => T), saveToLocalStorage?: boolean) => void,
() => void,
boolean,
string | null,
() => void,
() => void
];
Validation Example
Custom validation functions can be passed to ensure that the new state meets your criteria:
const isNotEmpty = (value: { name: string }): boolean => {
return value.name.trim().length > 0;
};
const [data, setData] = AM_ReduxState<{ name: string }>(
"data",
{ name: "mohmed" },
300,
[isNotEmpty]
);
FAQ
Q: What happens if localStorage contains corrupted data?
A: The hook will catch JSON parsing errors, log the error to the console, and remove the corrupted entry from localStorage.
Q: Can I switch between debounce and throttle?
A: Yes. Set the useThrottle parameter to true to use throttle instead of debounce.
Q: Does this library support auto-completion?
A: Absolutely. The library is fully typed with TypeScript, offering rich auto-completion in supported editors.
Contributing
We welcome contributions and suggestions to improve AM_ReduxState. If you have any ideas or bug reports, please open an issue or submit a pull request on the official repository.
Roadmap
Enhanced error handling: Add more detailed error logging and user notifications.
Improved performance: Explore optimizations for handling large or complex state objects.
Extended API: Consider adding additional configuration options and hooks based on community feedback.
License
This project is licensed under the MIT License.
Copyright
© A&M mohmed ahmed. All rights reserved.
