redux-saga-fetch-actions
v1.0.1
Published
Saga for consistent fetch api actions
Downloads
1
Maintainers
Readme
redux-saga-fetch-actions
Saga for consistent async actions.
Dispatch an action in FSA format with your desired prefix (default is "FETCH_").
dispatch({
type: "FETCH_WIDGETS",
payload: {
request: () => Promise.resolve([1, 2, 3, 4, 5]),
onSuccess: (response) => {
alert(response)
},
onFailure: (error) => {
alert(error)
}
},
meta: "Some data"
})
The saga will then dispatch a request action, and either a success or failure action, both in FSA format. The meta property will be passed through to both. If no meta is provided, it will be set to be the request function.
{
type: "WIDGETS_SUCCESS",
payload: [1,2,3,4,5] // The request response,
meta: "Some data"
}
{
type: "WIDGETS_FAILED",
payload: "Something went wrong!", // The exception error,
meta: "Some data"
error: true
}
Installation
npm install redux-saga-fetch-actions
import { all } from "redux-saga/effects";
import createSagaMiddleware from "@redux-saga/core";
import { fetchSaga } from "redux-saga-fetch-actions";
import { applyMiddleware, createStore } from "redux";
import { rootReducer } from "../reducers";
const sagaMiddleware = createSagaMiddleware();
export const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
export function* rootSaga() {
yield all([fetchSaga("FETCH_")]);
}
sagaMiddleware.run(rootSaga);
Saga Props
| Prop | Type | Description | | :--------------------------------- | :----: | :------------------------------: | | prefix(default = "FETCH_") | string | Prefix to trigger the fetch saga |
Action Payload Props
| Prop | Type | Description | | :----------------------- | :---------------------: | :-------------------------------------------: | | request(required) | () => Promise | Fetch request | | onSuccess | (response: any) => void | Function called if the request was successful | | onFailure | (error: Error) => void | Function called if the request failed |