1.0.5 • Published 2 years ago
thunk-request-statuses v1.0.5
Thunk Request Statuses
Purpose
If you are using createAsyncThunk
from @reduxjs/toolkit
, thunk-request-statuses
gives an ability to avoid a lot of isLoading statuses in your project and provide the simple API for subscribing on 3 statuses of your async action.
You can subscribe on the following states:
- isPending state
- isRejected state
- isFulfilled state
Basic example
request-user.thunk.ts
const requestUserThunk = createAsyncThunk('request-user', async () => {
const response = await fetch('https://some-url.com');
return response.json();
})
Components usage:
Now if you are interested in some status of your action,it is simple to subscribe on that in the template.
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useIsPending, useIsRejected, useIsFulfilled } from "thunk-request-statuses";
import { requestUserThunk } from "@store/user/request-user.thunk.ts";
export const UserPage = () => {
const dispatch = useDispatch();
const isPending = useIsPending(requestUserThunk);
const isFulfilled = useIsFulfilled(requestUserThunk);
const isRejected = useIsRejected(requestUserThunk);
useEffect(() => {
dispatch(requestUserThunk());
}, [])
useEffect(() => {
if(isFulfilled) {
alert('Fulfilled!');
}
if(isRejected) {
alert('Rejected!');
}
}, [isFulfilled, isRejected])
if(isPending) {
return <FullScreenLoader />
}
return (
/// ..
)
}
Installation
Open a Terminal in the project root and run:
yarn add react-request-statuses
or
npm i react-request-statuses
Setup
- Add
requestStatuses
reducer to your root reducer.
import { requestStatuses } from 'thunk-request-statuses';
export const rootReducer = combineReducers({
requestStatuses, // <- add here
// ...
})
1.0.5
2 years ago