Middleware for writing asynchronous actions in synchronous style

Overview

redux-sync-promise

Build Status NPM version Downloads

Middleware for writing asynchronous actions in synchronous style

Installation

$ npm install --save redux-sync-promise

Usage

Add middleware

import { APISync } from 'redux-sync-promise';

const api = APISync({/* options */});
const createMiddleware = applyMiddleware(thunk, api);
const store = createMiddleware(createStore)(reducer);

Action Examples

Every action will dispatch type name from types plus postfix.

// This example will dispatch PEOPLE_PENDING, PEOPLE_SUCCESS or PEOPLE_FAILURE
/*
 * Full example
 * */
export function getPeopleList(country, age) {
  return {
    types: 'PEOPLE',
    // this data will add in all functions like arguments
    data: {country, age},
    // disable dispatch PENDING event in this action
    off: {
      pending: true
    },
    name: getPeopleName,
    work: getPeopleWork
    food: getPeopleFood
  }
}

/*
 * Get people info
 * @param {object} state - store state
 * @param {function} dispatch - action dispatch function
 * @param {array} props - props in the data key in the action
 * */
async function getPeopleName(state, dispatch, props) {
  let {people: {entriesOnPage}} = state;
  let requestString = `people/?rows=${entriesOnPage}`;

  const {data: {people, total}} = await fetch(requestString);
  return {people, total};
}
// and so on ...

/*
 * Simple examples
 * */
 export function getUnicornList(data) {
   return {
     types: 'UNICORN',
     list: request.post('food/', data)
   }
 }

 export function getUnicornList(data) {
   return {
     types: 'UNICORN',
     list: request.post('list/', data),
     food: request.post('food/', data),
   }
 }

 export function getUnicornList() {
   return {
     types: 'UNICORN',
     list: async (state, dispatch, props) => {
       let rainbow = await getRainbow();
       return rainbow.data.colors
     }
   }
 }

 export function getUnicornList(data) {
   return {
     types: 'UNICORN',
     data: {...data},
     list: async (state, dispatch, props) => {
       let rainbow = await getRainbow();
       return rainbow.data.colors
     },
     food: async (state, dispatch, props) => {
       let rainbow = await getFood();
       return rainbow.data.colors
     }
   }
 }

 export function getUnicornList(data1, data2) {
   return {
     types: 'UNICORN',
     list: Promise.all([
      request.post('food/', data1),
      request.post('rainbow/',data2)
    ])
   }
 }

API

APISync exposes single constructor function for creating middleware.

APISync( options: Object )

// Full example
APISync({
	postfix: {
		pending: 'IS_PENDING',
		success: 'IS_SUCCESS'
		failure: 'IS_FAILURE'
	},
  // global enable/disable dispatching event
  off: {
    pending: false,
    success: false,
    failure: false,
  }
	onPending: (dispatch, data) => {
		console.log('some action api pending');
	},
	onSuccess: (dispatch, result, data) => {
		console.log('some action api success');
	},
	onError: (dispatch, error, data) => {
		// example use on errors
		if(err.status === 401)
	        dispatch({type: 'LOGOUT_SUCCESS'});

		console.log('some action api error');
	}
})

postfix

Add your custom action type postfix for API call.

Default: PENDING, SUCCESS, FAILURE

onPending

Callback when actions in progress

/*
 * @param {function} dispatch - action dispatch function
 * @param {object} data -  an array of props in the data key in the action
 */
onPending = (dispatch, data) => {}

onSuccess

Callback on success

/*
 * @param {function} dispatch - action dispatch function
 * @param {object} result - total result object
 * @param {object} data -  an array of props in the data key in the action
 */
onSuccess = (dispatch, result, data) => {}

onError

Callback on error

/*
 * @param {function} dispatch - action dispatch function
 * @param {object|string} error - total error
 * @param {object} data -  an array of props in the data key in the action
 */
onError = (dispatch, error, data) => {}

off

Global disable dispatching SUCCESS, PENDING or FAULURE event

off: {
  pending: false,
  success: false,
  failure: false,
}

Reducer create helper

Standart wrapper for create reducers. I use it on some projects , for this reason, he added to the package

import { createReducer } from 'redux-sync-promise';

export default createReducer(initialState, {
  [PEOPLE_SUCCESS](state, action) {
     return {...state}
  }
})

License

Copyright © 2016 Alexander Dukhovnyak

Released under the MIT license. See license for details.

You might also like...
Lightweight react-like library. Support for asynchronous rendering and hooks.

Recept · Lightweight react-like library. Like the name, this project is mainly based on the architectural idea of react, which can feel react more int

A simple middleware-style router for isomorphic JavaScript web apps

Universal Router A simple middleware-style router that can be used in both client-side and server-side applications. Visit Quickstart Guide (slides) |

React-animate-style - A react integration of animate.css (animate.style)

react-animate-style Easy animate react app with animate.css library Install With

React Hook for reading from and writing to the user's clipboard.

useClippy useClippy is a TypeScript-friendly React hook for reading from and writing to the user's clipboard. Not to be confused with Microsoft Office

A library for writing React components that automatically manage subscriptions to data sources simply by accessing them

ReSub A library for writing better React components and data stores. Uses automatic subscriptions to reduce code and avoid common data flow pitfalls.

✍️ Markdown writing application that's down right, neat.
✍️ Markdown writing application that's down right, neat.

✍️ Markdown writing application that's down right, neat.

A plugin example for writing reactions with the Figma plugin API
A plugin example for writing reactions with the Figma plugin API

🍜 figma-plugin-example-prototype-write The ability to write protoype interactions in the Figma plugin API has landed! This update allows plugins to c

JSXFields is a library for creating form field elements in React with a function call instead of writing raw JSX.

JSXFields is a library for creating form field elements in React with a function call instead of writing raw JSX. This is useful in a setting where you want to generate forms dynamically according to user input such as with a form building application like Wufoo.

 Reddit app writing in react-native + redux !
Reddit app writing in react-native + redux !

xReddit Reddit for Android, made withReact-Native. Adding support for iOS is on the way, adding support for OSX is also in plan!!! Build & Run s1 npm

An all in one preset for writing Preact apps with the vite bundler.

@preact/preset-vite An all in one preset for writing Preact apps with the vite bundler. Features: Sets up Hot Module Replacement via prefresh Enables

Document React components by declaring props definition and writing markdown.
Document React components by declaring props definition and writing markdown.

Document React components by declaring props definition and writing markdown.

Component that performs the effect of writing
Component that performs the effect of writing

React text Typing Installation $ npm add react-text-typing // OR $ yarn add react-text-typing Demo Examples import React from 'react'; import React

A nice and cute select which will let the users search inside the select options writing what they want to find.
A nice and cute select which will let the users search inside the select options writing what they want to find.

React Finder Select This is a small project whose objective is to supply an effective and easy to use solution for the common problems about the norma

The game wordle made with ReactJS, without writing a line of CSS
The game wordle made with ReactJS, without writing a line of CSS

I made Wordle XD Hello everyone 👋 , I am glad to see you here I know it ain't much but this is the game wordle (popular in twitter recently!) I made

This project allows you leverage Million's Virtual DOM while writing React code

This project allows you leverage Million's Virtual DOM while writing React code. Get faster rendering (a compiler optimizes virtual DOM beforehand) while ensuring the same developer experience React provides.

A template for all of you to create and deploy an Awesome Portfolio for free without writing code
A template for all of you to create and deploy an Awesome Portfolio for free without writing code

A template for all of you to create and deploy an Awesome Portfolio for free without writing code

A platform to enhance English writing skill as a learner or give feedback to others' essay as a tutor
A platform to enhance English writing skill as a learner or give feedback to others' essay as a tutor

English Writing Response Platform - BONUFO A platform to enhance English writing skill as a learner or give feedback to others' essay as a tutor Live

KeyKey - A typing practice tool writing in react.All ui is reference to keykey
KeyKey - A typing practice tool writing in react.All ui is reference to keykey

A typing practice tool writing in react.All ui is reference to keykey DEMO Features Keyboard and event listening text generator and input check

This is a Codespaces React template that leverages a Code Tour to guide beginners through writing their first lines of React.
This is a Codespaces React template that leverages a Code Tour to guide beginners through writing their first lines of React.

Learn React with Codespaces 📝 Welcome to your first Codespace running a popular UI framework called React! We've got everything fired up and running

Owner
Alexander Dukhovnyak
For me, the perfect interface is like having sex with an intelligent and beautiful girl. How not to twist, it's a pleasure to work!
Alexander Dukhovnyak
Analytics middleware for Redux

redux-analytics Analytics middleware for Redux. $ npm install --save redux-analytics Want to customise your metadata further? Check out redux-tap. Usa

Mark Dalgleish 490 Aug 5, 2022
A mock store for testing Redux async action creators and middleware.

redux-mock-store A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which

Redux 2.5k Jan 1, 2023
簡単なReact NativeのUI。Writing effective React Native App's style easier.

Tanjun Write React Native style in an easy way and restore the original design one to one. Get size from designer and use it in your app. Happy coding

阿邦 7 Mar 29, 2022
⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Tanner Linsley 32.1k Jan 8, 2023
🧭 Declarative, asynchronous routing for React.

Navi Declarative, asynchronous routing for React. Navi is a JavaScript library for declaratively mapping URLs to asynchronous content. It comes with:

Frontend Armory 2.1k Dec 23, 2022
🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️

A reactive database framework Build powerful React and React Native apps that scale from hundreds to tens of thousands of records and remain fast ⚡️ W

Nozbe 8.8k Jan 8, 2023
🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️

A reactive database framework Build powerful React and React Native apps that scale from hundreds to tens of thousands of records and remain fast ⚡️ W

Nozbe 8.8k Jan 3, 2023
Use-tasker - A react task runner for asynchronous things

useTasker A React Hook to schedule asynchronous things. Install yarn add use-tas

Boopathi Rajaa 3 Feb 23, 2022
A simple asynchronous React message popup utility

React Message A simple asynchronous React message popup utility, no needed React Context. So you can use it in anywhere. You just need to install Reac

寻 6 Sep 10, 2022
Implement Mini-React in 400 lines of code, a minimal model with asynchronous interruptible updates.

Mini-React Implement Mini-React in 400 lines of code, a minimal model with asynchronous interruptible updates. Demos A simple running screenshot: Intr

Zachary Lee 58 Jan 5, 2023