Coder Social home page Coder Social logo

typescript-fsa-redux-observable's Introduction

TypeScript FSA utilities for redux-observable

npm version Build Status

Installation

yarn add typescript-fsa-redux-observable

API

ofAction(action: ActionCreator)

Example:

// for actions
import actionCreatorFactory, { AnyAction, Action, Success } from 'typescript-fsa';

// for reducers
import { reducerWithInitialState } from 'typescript-fsa-reducers';
import { combineReducers } from 'redux';

//for epics
import { delay, map, tap, ignoreElements } from 'rxjs/operators';
import { ofAction, ofActionPayload } from 'typescript-fsa-redux-observable'; // <-- here
import { combineEpics, Epic, createEpicMiddleware } from 'redux-observable';

//reducer
import {createStore, applyMiddleware} from 'redux';


// action
const actionCreator = actionCreatorFactory();
const actions = {
    increment: actionCreator.async<undefined, undefined>('INCREMENT'),
    decrement: actionCreator.async<undefined, undefined>('DECREMENT')
};

// reducers & state

interface State {
    counter: number;
}

const counter = reducerWithInitialState(0)
    .case(actions.increment.done, state => state + 1)
    .case(actions.decrement.done, state => state - 1);
const rootReducer = combineReducers({
    counter
});

// epics
const counterIncrementEpic: Epic<AnyAction, Action<Success<undefined, undefined>>, State> =
    action$ =>
        action$.pipe(
            ofActionPayload(actions.increment.started),
            delay(300),
            map(payload => actions.increment.done({
                params: payload,
                result: undefined
            }))
        );

const counterDecrementEpic: Epic<AnyAction, Action<Success<undefined, undefined>>, State> =
    action$ =>
        action$.pipe(
            ofActionPayload(actions.decrement.started),
            delay(300),
            map(payload => actions.decrement.done({
                params: payload,
                result: undefined
            }))
        );

const loggingEpic: Epic<AnyAction, AnyAction, State> =
    action$ =>
        action$.pipe(
            ofAction(
                actions.decrement.started,
                actions.increment.started,
            ),
            tap(action => console.log(action.type)),
            ignoreElements()
        );


const rootEpic = combineEpics(
    counterIncrementEpic,
    counterDecrementEpic,
    loggingEpic,
);

const epicMiddleware = createEpicMiddleware<AnyAction, AnyAction, State>();
const store = createStore(rootReducer, applyMiddleware(epicMiddleware));
epicMiddleware.run(rootEpic);

// tool
async function sleep(time: number) {
    return new Promise<void>(resolve => {
        setTimeout(() => (resolve()), time)
    })
}

it("increment decrement test", async () => {
    expect(store.getState()).toEqual({ counter: 0 });

    store.dispatch(actions.increment.started(undefined));
    expect(store.getState()).toEqual({ counter: 0 });

    await sleep(300);
    expect(store.getState()).toEqual({ counter: 1 });

    store.dispatch(actions.decrement.started(undefined));
    expect(store.getState()).toEqual({ counter: 1 });

    await sleep(300);
    expect(store.getState()).toEqual({ counter: 0 })
});

typescript-fsa-redux-observable's People

Contributors

m0a avatar sgrishchenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

typescript-fsa-redux-observable's Issues

support RxJS 6

Thank you for useful module :)

This is a proposal (not PR).
In rxjs version 6, it is recommended to use pipe instead of prototype.
https://github.com/ReactiveX/rxjs/blob/91088dae1df097be2370c73300ffa11b27fd0100/doc/pipeable-operators.md

Here is a pipeable operator of ofAction.

import { ActionsObservable } from 'redux-observable';
import { Action, ActionCreator } from 'typescript-fsa';
import { filter } from 'rxjs/operators';
import { MonoTypeOperatorFunction } from 'rxjs';

export function ofAction<P>(
  actionCreator: ActionCreator<P>
): MonoTypeOperatorFunction<Action<P>> {
  return function(actions$) {
    return actions$.pipe(filter(actionCreator.match)) as ActionsObservable<
      Action<P>
    >;
  };
}

e.g.

import { ofAction } from 'typescript-fsa-redux-observable';

action$.pipe(
    ofAction(actions.someActionCreator),
    map(action => actions.otherActionCreator)
);

I think this is not the best answer, but it works.
Thanks!

Generated code is ES6

Could you please ship ES5 code (in the dist folder)?
The ES6 can cause problems with browser, UglifyJS and various other tools.
It should be enough to change target in tsconfig.json to es3 or es5.

Module not found

After installation i'm getting the following error:

Module not found: Error: Can't resolve 'typescript-fsa-redux-observable'

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, you’ll need to re-trigger Greenkeeper’s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organiszation’s settings page, under Installed GitHub Apps.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.