redux-thunk-wrapper
v1.0.4
Published
A React hook wrapper for Redux Toolkit async thunks with retries, loading, and error handling.
Maintainers
Readme
redux-thunk-wrapper
A reusable React hook to dispatch Redux Toolkit async thunks with built-in loading, retry, and **error handling ** support.
Features
- Works with
createAsyncThunkand custom thunk action creators - Supports automatic retries with configurable attempts
- Optional loading state for UI feedback
- Centralized error handling callback
- Fully typed with TypeScript
- Minimal boilerplate, clean component usage
Installation
npm install redux-thunk-wrapper
# or
yarn add redux-thunk-wrapperMake sure you have these peer dependencies installed as well:
react(>=16.8)react-redux(>=7.1)
Usage
import React, {useEffect} from "react";
import {useThunkWrapper} from "redux-thunk-wrapper";
import {fetchPostsByUser} from "./store/postsSlice";
function UserPosts({userId}: { userId: number }) {
// Wrap thunk with loading, retry and error handling
const [fetchPosts, loading] = useThunkWrapper(fetchPostsByUser, {
withLoading: true,
retry: 3,
onError: (error) => alert("Failed to load posts: " + error.message),
});
useEffect(() => {
fetchPosts(userId);
}, [fetchPosts, userId]);
if (loading) return <p>Loading...</p>;
return <div>Posts loaded! {/* Render your posts here */}</div>;
}API
useThunkWrapper(actionCreator, options?)
actionCreator- a Redux thunk action creator (sync or async, supportscreateAsyncThunk)options(optional):withLoading(boolean): whether to track loading state (default:false)retry(boolean | number):falseor omitted: no retry (1 attempt)true: retry once (2 attempts total)number: max retry attempts
onError((error: any) => void): callback when an error occurs
Returns: [runThunk, loading] tuple where:
runThunkis an async function that dispatches the thunk with argumentsloadingis a boolean indicating whether the thunk is in progress (ifwithLoadingis enabled)
Development
- Clone the repo
- Run
npm install - Build with
npm run build - Run tests (if any)
License
MIT © Jingx
Contributing
Feel free to open issues or PRs. All contributions are welcome!
Author
Jingx – [email protected]
