redux-iterate

1.0.3 • Public • Published

Redux iterator middleware

Use (async) generators as action creators to yield actions. This middleware will handle dispatched iterators ('nextable' objects).

NPM Version NPM Downloads GitHub issues Licence

Installation

npm install --save redux-iterate

Then, to enable Iterator Middleware, use applyMiddleware():

import { createStore, applyMiddleware } from 'redux';
import iterate from 'redux-iterate';
import rootReducer from './reducers';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(iterate)
);

Usage

You can use generators as action creators with this middleware enabled.

Yield action objects to dispatch them! Forget about wrapping each time with dispatch:

// Action creator
export const signIn = async function* (payload) {
  const { username, password } = payload;
  let state = yield; // won't be dispatched, just returns current state
  yield signInStart();
  try {
    const response = await axios.post(API_SIGN_IN, { username, password });
    yield signInEnd();
    yield signInSuccess(response.data);
    return username;
  } catch (error) {
    yield signInEnd();
    yield signInError(error);
  }
};

yield always returns a new state. If you yield nothing (undefined), it just returns current state (nothing happens):

// Inside generator
const params = getDataFromState(yield); // yield expression

To invoke your action creator/generator directly wrap it into a dispatch call using connect from react-redux or bindActionCreators from redux.

If you want to do something when your binded action is done, return some data from generator and get it with .then:

signIn().then(username => {
  console.log(username)
});

Yep, nice) Tell your friend.

Author

@doasync

Package Sidebar

Install

npm i redux-iterate

Weekly Downloads

1

Version

1.0.3

License

MIT

Last publish

Collaborators

  • doasync