npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@panderalabs/redux-fetch-middleware

v1.2.1

Published

Redux middleware enabling fetch actions

Downloads

5

Readme

Redux Fetch Middleware

npm install --save @panderalabs/redux-fetch-middleware
npm install --save whatwg-fetch // It's assumed that fetch is available on the client you're using

Why Do I Need This?

This middleware allows you to dispatch actions that trigger an API fetch call, in the process dispatching new actions when the transaction has started, completed successfully, or failed.

Instead of doing this:

const FOO_FETCH_SUCCESS = 'FETCH_FOO_SUCCESS';
function fooFetchSuccess(result) {
  return {
    type: FOO_FETCH_SUCCESS,
    payload: result,
  };
}

const FOO_FETCH_FAILURE = 'FETCH_FOO_FAILURE';
function fooFetchFailure(err) {
  return {
    type: FOO_FETCH_FAILURE,
    payload: err,
    error: true,
  };
}

const FOO_FETCH_STARTED = 'FETCH_FOO_STARTED';
function fooFetchStarted() {
  return {
    type: FOO_FETCH_STARTED,
  };
}

function fetchFoo() {
  return (dispatch, getState) => {
    dispatch(fooFetchStarted());
    const token = getState().user.token;
    fetch('/api/foo', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`
      },
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText);
      }
      return result.json();
    })
    .then(result => dispatch(fooFetchSuccess(result)))
    .catch(err => dispatch(fooFetchFailure(err)))
  };
}

You can now do this:

const FOO_FETCH = 'FOO_FETCH';
function fetchFoo() {
  return {
    type: 'FOO_FETCH',
    meta: {
      type: '@api',
      method: 'GET',
      url: '/foo'
    }
  }
}

It's intended to use as a way to communicate with your primary, authenticated (using the Authorization header) api. If you want to communicate with 3rd party apis, you can overwrite the authorization header and any other configs by passing in a config object with the headers defined.

How do I use it

Any time you create an action with a meta object with type @api, the middleware will automatically make a fetch call using the method and url also defined on your meta object. If you're making a POST request, the payload from your action will be set as the body in the request.

const FOO_FETCH = 'FOO_FETCH';

function getFoo() {
  return {
    type: FOO_FETCH,
    meta: {
      type: '@api',
      method: 'GET',
      url: '/foo',
    }
  };
}

Installation

npm install --save @panderasystems/redux-fetch-middleware

Too enable it in your project, use applyMiddleware():

import { createStore, applyMiddleware } from 'redux';
import createFetchMiddleware from '@panderasystems/redux-fetch-middleware';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(createFetchMiddleware())
);

Available options

When creating the middleware, you have a couple of options available:

import createFetchMiddleware from '@panderasystems/redux-fetch-middleware';

const fetchMiddleware = createFetchMiddleware(
  state => state.user.token, // A selector to get the Authorization token out of the redux state
  '/api', // The base URL for your api- This can be a fully-qualified URL or just a path
)

More Details

// Posting data
const FOO_POST = 'FOO_POST';
function postFoo(data) {
  return {
    type: FOO_POST,
    payload: data, // payload is set as the body of the request
    meta: {
      type: '@api',
      method: 'POST',
      url: '/foo'
    }
  }
}

// Other configs:
function postFoo(data) {
  type: FOO_POST,
  payload: data,
  meta: {
    type: '@api',
    url: '/foo',
    method: 'GET', // optional: defaults to GET
    config: { // optional: Supports any configuration that can be passed into fetch
      // Note: method and body will be overwritten by the method and payload passed into the meta object
      headers: {
        'Content-Type': 'application/json',
        credentials: 'same-origin', // Used to send across cookies
      }
    }
  }
}

function getExternalResource() {
  type: 'EXTERNAL_GET',
  meta: {
    type: '@api',
    url: 'http://example.com/api/foos',
    config: {
      headers: {
        Authorization: null // Will overwrite the default authorization header
      }
    }
  }
}

Pass Back Meta

When working with sub-resources it is often benificial for the reducers to know about the parent. Instead of creating a seprate success action to handle this extraction like so.

const GET_SUB_RESOURCE_SUCCESS = 'GET_SUB_RESOURCE_SUCCESS';
function getSubResourceSuccess(result) {
  return {
    type: GET_SUB_RESOURCE_SUCCESS,
    payload: result,
  };
}

function getSubResource(parentId) {
  function action() {
    type: 'SUB_RESOURCE_GET',
    meta: {
      type: '@api',
      url: `http://example.com/api/foos/${parentId}/bars`,
    }
  }

  dispatch(apiAction())
     // dispatch apiAction, on success pass back subResource and parentId as payload.
    .then(({ subResource }) => dispatch(getSubResoucreSuccess({ subResource, parentId }))
}

we can now just do this.

function getSubResource(parentId) {
  type: 'GET_SUB_RESOURCE',
  meta: {
    type: '@api',
    url: `http://example.com/api/foo/${parentId}/bars`,
    // pass in anything you want to comeback as meta.
    parentId,
  }
}

// result will look like
// { payload: subResource, meta: { parentId }}

A Promise is always returned from the dispatch of this action and will be resolved/rejected once the API call is completed. If you want to chain your api calls, feel free to do that!

dispatch(getFoo())
  .then(dispatch(postFoo({foo: 'bar'})))
  .then(dispatch(getExternalResource()))
  // It's not necessary to catch this error as the FAILURE action will be dispatched automatically
  .catch((err) => console.log('Error in the chain'))

Error Messaging

If you receive an error from your fetch call, a */FAILURE action will be dispatched, the contents of which will contain a status code, status text, and original response. The payload will look like this:

{
  type: '@api/action/FAILURE',
  err: {
    code: 404,
    message: 'Not Found',
    response: { ... } // The full body of the response from Fetch (Which you can call .json() on if it's a json payload)
  },
  meta: { ... } // Any meta data attached to the original action
}