@mratsamy/fetch-redux-middleware

3.0.4 • Public • Published

A simple redux middleware that makes it a bit easier to dispatch a fetch request. Uses es6 promise package and portable fetch for an isomorphic fetch library with poyfill for older browsers.

Note if you're also using thunk middleware you should declare it prior to that to ensure there aren't any side effects.

Parameters

  1. StoreToken, defaults to false. Expects a string value, which is the redux store object's key to use for fetch requests.
  2. defaultParameters. Defaults to an empty object, used to set default parameters on all requests if missing from the fetch dispatch, which include the method (string), url (string), cache (string) and headers (object) values.
  3. logRequest. Boolean, defaults to false, will console.log the fetch request's second parameter before dispatching.
  4. fetchType. String, defaults to FETCH. This is the action.type string that the middileware will be looking to compare against.

URL, with a value of url is required on the intercepted dispatch object. If the middleware intercepts a dispatch with a missing url value, the middleware returns an Error which should be caught in a try/catch loop.

// using defaults
    const { fetchMiddleware } = require('fetch-redux-middleware')

    /* **Note**, if using thunk middleware should be declared before declaring thunk */
    const middleware = [
        fetchMiddleware()
    ]

    const store = createStore(applyMiddleware(middleware))
====================================================================
try {
    let result = await dispatch(type: "FETCH", url:"<target url>") /* doesn't include an authorization header w/ a redux store token value. */
} catch {
    ...
}

Or overriding the default values, body values are serialized before fetched.

const { fetchMiddleware } = require('fetch-redux-middleware')

const middleware = [
    fetchMiddleware("USER_TOKEN", {}, false, "FETCH-PROMISE") /* first parameter is the store object's value for the token, second the dispatch value action.type to intercept */
]

const store = createStore(applyMiddleware(middleware))
====================================================================
try {
    let result = await dispatch({type: "FETCH-PROMISE", url: <target url, required>, headers: {<header object, default is empty object>}, cache: "<cache response, default is `reload`>", method: <request method, default is `GET`>, body: {k:v}}, queryParams: {k:v})
} catch {
    ...
}

Readme

Keywords

none

Package Sidebar

Install

npm i @mratsamy/fetch-redux-middleware

Weekly Downloads

1

Version

3.0.4

License

ISC

Unpacked Size

11.9 kB

Total Files

5

Last publish

Collaborators

  • mratsamy