All Projects → CharlesStover → fetch-action-creator

CharlesStover / fetch-action-creator

Licence: MIT license
Fetches using standardized, four-part asynchronous actions for redux-thunk.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to fetch-action-creator

react-multi-context
Manage multiple React 16 contexts with a single component.
Stars: ✭ 19 (-32.14%)
Mutual labels:  mocha, travis-ci, travis, npm-module, npmjs, travisci
react-innertext
Returns the innerText of a React JSX object.
Stars: ✭ 37 (+32.14%)
Mutual labels:  mocha, travis-ci, chai, travis, npm-module, travisci
react-testing-mocha-chai-enzyme
A solid test setup for React components with Mocha, Chai, Sinon, Enzyme in a Webpack/Babel application.
Stars: ✭ 48 (+71.43%)
Mutual labels:  mocha, travis-ci, chai, travis
Reactn
React, but with built-in global state management.
Stars: ✭ 1,906 (+6707.14%)
Mutual labels:  travis-ci, travis, travisci
js-stack-from-scratch
🌺 Russian translation of "JavaScript Stack from Scratch" from the React-Theming developers https://github.com/sm-react/react-theming
Stars: ✭ 394 (+1307.14%)
Mutual labels:  mocha, chai, npm-module
react-native-web-view
An implementation of React Native's WebView that allows for postMessage on iOS devices.
Stars: ✭ 13 (-53.57%)
Mutual labels:  travis-ci, npmjs, travisci
alexa-skill-boilerplate
An easy to use Amazon Alexa Skill Boilerplate for fast skill creation
Stars: ✭ 54 (+92.86%)
Mutual labels:  mocha, travis-ci, chai
Chakram
REST API test framework. BDD and exploits promises
Stars: ✭ 912 (+3157.14%)
Mutual labels:  mocha, chai
Bombanauts
Bombanauts, inspired by the original Bomberman game, is a 3D multiplayer online battle arena (MOBA) game where players can throw bombs at each other, make boxes explode, and even other players!
Stars: ✭ 54 (+92.86%)
Mutual labels:  mocha, chai
Karma Webpack Example
Karma + Webpack + Mocha + Chai + Istanbul
Stars: ✭ 88 (+214.29%)
Mutual labels:  mocha, chai
Javascript Testing Best Practices
📗🌐 🚢 Comprehensive and exhaustive JavaScript & Node.js testing best practices (August 2021)
Stars: ✭ 13,976 (+49814.29%)
Mutual labels:  mocha, chai
Jobsort
job board that queries hacker news who is hiring job listings from a database and sorts by tech the user knows and how well the user knows them
Stars: ✭ 20 (-28.57%)
Mutual labels:  mocha, chai
Tvrboreact
Dream starter project: React, Redux, React Router, Webpack
Stars: ✭ 13 (-53.57%)
Mutual labels:  mocha, chai
React Base
atSistemas React/Redux Isomorphic Platform
Stars: ✭ 82 (+192.86%)
Mutual labels:  mocha, chai
Unit Test Demo
一步一步介绍如何给项目添加单元测试
Stars: ✭ 766 (+2635.71%)
Mutual labels:  mocha, travis-ci
Hapi Starter Kit
Hapi.js based REST boilerplate which uses latest ES7/ES8 features (async/await) with code coverage and follows best pratices
Stars: ✭ 103 (+267.86%)
Mutual labels:  mocha, travis-ci
Jest Codemods
Codemods for migrating to Jest https://github.com/facebook/jest 👾
Stars: ✭ 731 (+2510.71%)
Mutual labels:  mocha, chai
Typescript Restful Starter
Node.js + ExpressJS + Joi + Typeorm + Typescript + JWT + ES2015 + Clustering + Tslint + Mocha + Chai
Stars: ✭ 97 (+246.43%)
Mutual labels:  mocha, chai
chai-exclude
Exclude keys to compare from a deep equal operation with chai expect or assert.
Stars: ✭ 33 (+17.86%)
Mutual labels:  mocha, chai
Redux Actions Assertions
Simplify testing of redux action and async action creators
Stars: ✭ 177 (+532.14%)
Mutual labels:  mocha, chai

Fetch Action Creator Tweet

Fetches using standardized, four-part asynchronous actions for redux-thunk.

Dispatch a single, asynchronous action that fetches a request, and your redux store will receive corresponding actions when your fetch API (1) requests, (2) resolves a response, (3) rejects an error, and/or (4) is aborted.

version minified size minzipped size downloads build

Install

  • npm install fetch-action-creator --save or
  • yarn add fetch-action-creator

Your redux store must be using the redux-thunk middleware.

Basic Example

import fetchActionCreator from 'fetch-action-creator';

const fetchEmployees = () =>
  fetchActionCreator(

    // Included in the action types received by your redux store.
    'EMPLOYEES',

    // URL to fetch.
    'https://my.business.com/employees.json'
  );

The above example will send a REQUEST_EMPLOYEES action to the redux store, followed by one of the following: ABORT_EMPLOYEES if the request was aborted, REJECT_EMPLOYEES if an error occurred, or RESOLVE_EMPLOYEES if the data was received successfully.

See the documentation for a list of action properties.

Advanced Example

import fetchActionCreator from 'fetch-action-creator';

// We want to include an employee's name in the fetch request.
const fetchAddEmployee = name =>
  fetchActionCreator(

    // Included in the action types received by your redux store.
    'ADD_EMPLOYEE',

    // URL to fetch.
    'https://my.business.com/employees.json',

    // Fetch options are configurable.
    {
      body: name,
      headers: {
        'Content-Type': 'text/plain; charset=utf-8'
      },
      method: 'POST'
    }

    // Action mutators can change the default actions sent to the redux reducers.
    {

      // An object mutator will EXTEND the default action sent to the redux reducer.
      // The abort action will now have a name property equal to the one passed to fetchAddEmployee.
      onAbort: { name }

      // The reject action will now have a name property equal to the one passed to fetchAddEmployee
      //    and a timestamp property equal to the time that the error occurred.
      onReject: {
        name,
        timestamp: Date.now()
      },

      // A function mutator will RECEIVE the default action sent and mutate it before passing it to the redux reducer.
      // The request action will now have a name property equal to the one passed to fetchAddEmployee.
      onRequest: requestAction => ({
        ...requestAction,
        name
      }),

      // The resolve action will now have a name property equal to the one passed to fetchAddEmployee
      //    and a timestamp property equal to the time that the error occurred.
      // You may mutate the action however you want.
      onResolve: resolveAction => {
        resolveAction.timestamp = Date.now();
        if (name.endsWith('*')) {
          resolveAction.type = 'RESOLVE_ADD_MANAGER';
        }
        return {
          ...resolveAction,
          name
        };
      }
    },

    // A conditional function will prevent the fetch request if it returns false.
    // The conditional function receives the current redux state as a parameter.
    state => {

      // If this request is already loading (handled in the reducer),
      //    don't make the same request again.
      if (state.employees[name].status === 'loading') {
        return false;
      }

      // People named Bob aren't allowed to work here.
      if (name === 'Bob') {
        return false;
      }

      // Allow the addition of anyone else.
      return true;
    }
  );

Parameters

id: string

An ID used to generate the types for each dispatched action.

Example: An ID of ADD_EMPLOYEE will dispatch the actions REQUEST_ADD_EMPLOYEE, RESOLVE_ADD_EMPLOYEE, REJECT_ADD_EMPLOYEE, and ABORT_ADD_EMPLOYEE.

url: string

The URL to which you are dispatching a fetch request.

See also: fetch parameters on MDN

init: null | RequestInit | (state?: Object) => RequestInit

The fetch options which you are including in your fetch request or a function that returns said options, taking the current state as a parameter.

See also: fetch parameters on MDN

Default: Empty object.

actions: Actions | null

An object of action mutators that will change the default actions that are dispatched to the redux reducers.

The keys of this object may be:

  • onAbort, which is used when your fetch request is aborted
  • onReject, which is used when your fetch request encountered an error
  • onRequest, which is used when your fetch request has been initiated
  • onResolve, which is used whe nyour fetch request has resolved successfully

The values of this object may be an object, which will be merged with the default action.

{
  onAbort: { myKey: 'myValue' }
}
// creates
{
  myKey: 'myValue',
  type: 'ABORT_ID'
}

The values of this object may alternatively be a function, which will receive the default action and return a changed action.

{
  onAbort: abortAction => ({
    type: abortAction.type.split('').reverse().join('')
  })
}
// creates
{
  type: 'DI_TROBA'
}

Action properties

  • onAbort

    • no additional properties
  • onReject

    • error contains a string with the error message. This may be either a JavaScript error or server response.

    • statusCode contains an integer value of the response status code, e.g. 404.

  • onRequest

    • abortController contains an AbortController instance.

      If you desire to abort any of your fetch requests, you should store this instance in your redux state.

      If the user's browser does not support aborting requests, the value will be null.

  • onResolve

    • body contains the body of the response. This can be a JavaScript object or string.

    • headers contains an instance of Headers with which the server responded to the request.

    • statusCode contains an integer value of the response status code, e.g. 200.

conditional?: (state: Object) => boolean

If present, this function is called prior to the fetch request.

If it returns true, the fetch request will continue. If it returns false, the entire asynchronous action will be ignored.

The parameter of this function is a current snapshot of your redux state.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].