1.0.1 • Published 4 years ago

redux-saga-fetch-actions v1.0.1

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

redux-saga-fetch-actions

CI Status npm version

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

PropTypeDescription
prefix(default = "FETCH_")stringPrefix to trigger the fetch saga

Action Payload Props

PropTypeDescription
request(required)() => PromiseFetch request
onSuccess(response: any) => voidFunction called if the request was successful
onFailure(error: Error) => voidFunction called if the request failed