Coder Social home page Coder Social logo

cyclejs-community / redux-cycles Goto Github PK

View Code? Open in Web Editor NEW
747.0 22.0 30.0 114 KB

Bring functional reactive programming to Redux using Cycle.js

License: MIT License

JavaScript 99.21% HTML 0.79%
redux cycle-driver cyclejs cycle react side-effect reactive redux-cycle-middleware middleware functional-reactive-programming

redux-cycles's Introduction

Redux-cycles

Redux + Cycle.js = Love

Handle redux async actions using Cycle.js.

Build Status

Table of Contents

Install

npm install --save redux-cycles

Then use createCycleMiddleware() which returns the redux middleware function with two driver factories attached: makeActionDriver() and makeStateDriver(). Use them when you call the Cycle run function (can be installed via npm install --save @cycle/run).

import { run } from '@cycle/run';
import { createCycleMiddleware } from 'redux-cycles';

function main(sources) {
  const pong$ = sources.ACTION
    .filter(action => action.type === 'PING')
    .mapTo({ type: 'PONG' });

  return {
    ACTION: pong$
  }
}

const cycleMiddleware = createCycleMiddleware();
const { makeActionDriver } = cycleMiddleware;

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

run(main, {
  ACTION: makeActionDriver()
})

By default @cycle/run uses xstream. If you want to use another streaming library simply import it and use its run method instead.

For RxJS:

import { run } from '@cycle/rxjs-run';

For Most.js:

import { run } from '@cycle/most-run';

Example

Try out this JS Bin.

See a real world example: cycle autocomplete.

Why?

There already are several side-effects solutions in the Redux ecosystem:

Why create yet another one?

The intention with redux-cycles was not to worsen the "JavaScript fatigue". Rather it provides a solution that solves several problems attributable to the currently available libraries.

  • Respond to actions as they happen, from the side.

    Redux-thunk forces you to put your logic directly into the action creator. This means that all the logic caused by a particular action is located in one place... which doesn't do the readability a favor. It also means cross-cutting concerns like analytics get spread out across many files and functions.

    Redux-cycles, instead, joins redux-saga and redux-observable in allowing you to respond to any action without embedding all your logic inside an action creator.

  • Declarative side-effects.

    For several reasons: code clarity and testability.

    With redux-thunk and redux-observable you just smash everything together.

    Redux-saga does make testing easier to an extent, but side-effects are still ad-hoc.

    Redux-cycles, powered by Cycle.js, introduces an abstraction for reaching into the real world in an explicit manner.

  • Statically typable.

    Because static typing helps you catch several types of mistakes early on. It also allows you to model data and relationships in your program upfront.

    Redux-saga falls short in the typing department... but it's not its fault entirely. The JS generator syntax is tricky to type, and even when you try to, you'll find that typing anything inside the catch/finally blocks will lead to unexpected behavior.

    Observables, on the other hand, are easier to type.

I already know Redux-thunk

If you already know Redux-thunk, but find it limiting or clunky, Redux-cycles can help you to:

  • Move business logic out of action creators, leaving them pure and simple.

You don't necessarily need Redux-cycles if your goal is only that. You might find Redux-saga to be easier to switch to.

I already know Redux-saga

Redux-cycles can help you to:

  • Handle your side-effects declaratively.

    Side-effect handling in Redux-saga makes testing easier compared to thunks, but you're still ultimately doing glorified function calls. The Cycle.js architecture pushes side-effect handling further to the edges of your application, leaving your "cycles" operate on pure streams.

  • Type your business logic.

    Most of your business logic lives in sagas... and they are hard/impossible to statically type. Have you had silly bugs in your sagas that Flow could have caught? I sure had.

I already know Redux-observable

Redux-cycles appears to be similar to Redux-observable... which it is, due to embracing observables. So why might you want to try Redux-cycles?

In a word: easier side-effect handling. With Redux-observable your side-effectful code is scattered through all your epics, directly.

It's hard to test. The code is less legible.

Do I have to buy all-in?

Should you go ahead and rewrite the entirety of your application in Redux-cycles to take advantage of it?

Not at all.

It's not the best strategy really. What you might want to do instead is to identify a small distinct "category" of side-effectful logic in your current side-effect model, and try transitioning only this part to use Redux-cycles, and see how you feel.

A great example of a small category like that could be:

  • local storage calls
  • payments API

The domain API layer often is not the easiest one to switch, so if you're thinking that... think of something smaller :)

Redux-saga can still be valuable, even if using Redux-cycles. Certain sagas read crystal clear; sagas that orchestrate user flow.

Like onboarding maybe: after the user signs up, and adds two todos, show a "keep going!" popup.

This kind of logic fits the imperative sagas model perfectly, and it will likely look more cryptic if you try to redo it reactively.

Life's not all-or-nothing, you can definitely use Redux-cycles and Redux-saga side-by-side.

What's this Cycle thing anyway?

Cycle.js is an interesting and unusual way of representing real-world programs.

The program is represented as a pure function, which takes in some sources about events in the real world (think a stream of Redux actions), does something with it, and returns sinks, aka streams with commands to be performed.

stream
is like an asynchronous, always-changing array of values
source
is a stream of real-world events as they happen
sink
is a stream of commands to be performed
a cycle (not to be confused with Cycle.js the library)
is a building block of Cycle.js, a function which takes sources (at least ACTION and STATE), and returns sinks

Redux-cycles provides an ACTION source, which is a stream of Redux actions, and listens to the ACTION sink.

function main(sources) {
  const pong$ = sources.ACTION
    .filter(action => action.type === 'PING')
    .mapTo({ type: 'PONG' });

  return {
    ACTION: pong$
  }
}

Custom side-effects are handled similarly — by providing a different source and listening to a different sink. An example with HTTP requests will be shown later in this readme.

Aside: while the Cycle.js website aims to sell you on Cycle.js for everything—including the view layer—you do not have to use Cycle like that. With Redux-cycles, you are effectively using Cycle only for side-effect management, leaving the view to React, and the state to Redux.

What does this look like?

Here's how Async is done using redux-observable. The problem is that we still have side-effects in our epics (ajax.getJSON). This means that we're still writing imperative code:

const fetchUserEpic = action$ =>
  action$.ofType(FETCH_USER)
    .mergeMap(action =>
      ajax.getJSON(`https://api.github.com/users/${action.payload}`)
        .map(fetchUserFulfilled)
    );

With Cycle.js we can push them even further outside our app using drivers, allowing us to write entirely declarative code:

function main(sources) {
  const request$ = sources.ACTION
    .filter(action => action.type === FETCH_USER)
    .map(action => ({
      url: `https://api.github.com/users/${action.payload}`,
      category: 'users',
    }));

  const action$ = sources.HTTP
    .select('users')
    .flatten()
    .map(fetchUserFulfilled);

  return {
    ACTION: action$,
    HTTP: request$
  };
}

This middleware intercepts Redux actions and allows us to handle them using Cycle.js in a pure data-flow manner, without side effects. It was heavily inspired by redux-observable, but instead of epics there's an ACTION driver observable with the same actions-in, actions-out concept. The main difference is that you can handle them inside the Cycle.js loop and therefore take advantage of the power of Cycle.js functional reactive programming paradigms.

Drivers

Redux-cycles ships with two drivers:

  • makeActionDriver(), which is a read-write driver, allowing to react to actions that have just happened, as well as to dispatch new actions.
  • makeStateDriver(), which is a read-only driver that streams the current redux state. It's a reactive counterpart of the yield select(state => state) effect in Redux-saga.
import sampleCombine from 'xstream/extra/sampleCombine'

function main(sources) {
  const state$ = sources.STATE;
  const isOdd$ = state$.map(state => state.counter % 2 === 0);
  const increment$ = sources.ACTION
    .filter(action => action.type === INCREMENT_IF_ODD)
    .compose(sampleCombine(isOdd$))
    .map(([ action, isOdd ]) => isOdd ? increment() : null)
    .filter(action => action);

  return {
    ACTION: increment$
  };
}

Here's an example on how the STATE driver works.

Utils

combineCycles

Redux-cycles ships with a combineCycles util. As the name suggests, it allows you to take multiple cycle apps (main functions) and combine them into a single one.

Example:

import { combineCycles } from 'redux-cycles';

// import all your cycle apps (main functions) you intend to use with the middleware:
import fetchReposByUser from './fetchReposByUser';
import searchUsers from './searchUsers';
import clearSearchResults from './clearSearchResults';

export default combineCycles(
  fetchReposByUser,
  searchUsers,
  clearSearchResults
);

You can see it used in the provided example.

Testing

Since your main Cycle functions are pure dataflow, you can test them quite easily by giving streams as input and expecting specific streams as outputs. Checkout these example tests. Also checkout the cyclejs/time project, which should work perfectly with redux-cycles.

Why not just use Cycle.js?

Mainly because Cycle.js does not say anything about how to handle state, so Redux, which has specific rules for state management, is something that can be used along with Cycle.js. This middleware allows you to continue using your Redux/React stack, while allowing you to get your hands wet with FRP and Cycle.js.

What's the difference between "adding Redux to Cycle.js" and "adding Cycle.js to Redux"?

This middleware doesn't mix Cycle.js with Redux/React at all (like other cycle-redux middlewares do). It behaves completely separately and it's meant to (i) intercept actions, (ii) react upon them functionally and purely, and (iii) dispatch new actions. So you can build your whole app without this middleware, then once you're ready to do async stuff, you can plug it in to handle your async stuff with Cycle.

You should think of this middleware as a different option to handle side-effects in React/Redux apps. Currently there's redux-observable and redux-saga (which uses generators). However, they're both imperative and non-reactive ways of doing async. This middleware is a way of handling your side effects in a pure and reactive way using Cycle.js.

redux-cycles's People

Contributors

bzums avatar goodmind avatar goshacmd avatar lmatteis avatar nickbalestra avatar stevemao 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

redux-cycles's Issues

State should be passed with the action

Hey glad to see someone finally open sourced this approach. Something I have found to typically be true when using this approach internally is that you need the state with the action. This is useful as you will want to select a piece of state to conditionally decide if enough effect should sink. For example, you may want to check if you already have state for a given api before requesting it from the api again.

Request for a complex real world example

Hi,

I got really interested in redux-cycles. But, I am new to streams. Is it possible to add a an example project where there will be multiple async actions in a queue?

For eg. upon selecting an item from the list, a popup displayed which shows different kinds of data about the item, in which each data is the result of an async action.

Thanks much.

Better docs [to do]

This is a spike to organize thoughts and resources relating to docs. (Feel free to tag this one as a to-do or something)

As someone who's tried several existing side-effect models for Redux and Cycle, the README was just enough for me to see what this is about. However, this is not going to be the case for everyone, therefore we should consider an effort to improve the docs.

Throwing a couple of my thoughts:

  • identify target audiences: redux-saga and redux-observable users
  • appeal to TAs individually: maybe have separate sections about redux-cycle vs saga and redux-cycle vs redux-observable. pros and cons, differences in approaches
  • observables are typeable, whereas generators are hard to type (yield can't be typed. yield* can, but it can't be used in the catch/finally blocks, greatly limiting their usefulness — this is something I discovered making redux-typed-saga)
  • briefly introduce observables and Cycle.js and link to the official docs and other useful resources
  • page on side-effect handling. common scenarios
  • encourage custom drivers for side-effects (analytics, native functionality, etc; whereas the official docs seem to kind of oppose them)
  • commonly needed functionalities translated from pure react/sagas/observables to redux-cycle
  • more examples
  • GitHub pages to host the docs

Action from an http requetis fired twice

I have a component that at componentDidMount will fire an action that makes an http request.
What I want is to set an isFetching flag in the reducer.
Everything works as expected the first time I load the component, but the second the flag isFetching is never set to true.
I played just a little with the middleware during this weekend so I'm not really sure why I have this problem.

This is my main, I just readapted the code from one of the example.

const fetchPostById = (sources) => {
  const post$ = sources.ACTION
    .filter(action => action.type === ActionTypes.POST_REQUESTED)
    .map(action => action.postId);

  const request$ = post$
    .map(postId => ({
      url: `${BASE_URL}posts/${postId}`,
      category: 'post'
    }));

  const response$ = sources.HTTP
    .select('post')
    .flatten();

  const action$ = xs.combine(post$, response$)
    .map(arr => actions.receivePostById(arr[0], arr[1].body));

  return {
    ACTION: action$,
    HTTP: request$
  }
}

And this is the reducer:

const post = (state = initialPost, action) => {
  switch (action.type) {
    case 'POST_REQUESTED':
      return {
        ...state,
        isFetching: true,
      };
    case 'POST_RECEIVED':
      return {
        ...state,
        isFetching: false,
        [action.postId]: action.post,
      };
    default:
      return state;
  }
};

If I log what's going on with my request, I can see that isFetching is false at the beginning, then the action POST_REQUESTED is fired and isFetching is set to true. When POST_RECEIVED is being fired (from the cycle code) isFetching goes back to false. That's the normal case.
On the next time POST_RECEIVED is being fired two times for the same action and isFetching flag is never set to true.

screen shot 2017-02-27 at 18 19 34

You can see an online version here https://dbertella.github.io/food-and-quote/ in case.
Am I missing something?

Hot reloading

Someone on gitter pointed out that hot reloading isn't possible with redux-cycles. We should have a solution for this. Tagging this as enhancement

combineCycles

Hi Luca,

as I've starting playing with your awesome project, I found myself using something similar to combineEpics&co. Here is how it looks like.

In the example you provided could be used like:

// inside redux-cycle-middleware/example/cycle/index.js
...
import { combineCycles } from 'redux-cycle-middleware'
...
function fetchReposByUser(sources) {...}
function searchUsers(sources) {...}
...
export default combineCycles(fetchReposByUser, searchUsers)

Let me know what you think, happy to open a PR if you feel like it will make sense to have it within redux-cycle-middleware

Travis for `example` dir

So I'd like to test the example project (which is meant to be a separate project with its own package.json) using travis. Any thoughts on configuring this? @nickbalestra

Typescript definitions are not added to the build

Hey,

it seems like there are typescript type definitions (see #37) but there are not added to the build and therefore not available when using this lib in your project without further ado.

Or am I missing something here? If not, I would happily provide a PR.

Best

Support multiple stream libraries

Currently createCycleMiddleware() decides which stream library to use and it defaults xstream-run. It would be nice to allow users to select which run method to call, hence which stream library to use - and our driver internally should support most common stream libs using runStreamAdapter.

TypeScript Type Declarations

It is quite odd that this library written in JS because on the other side CycleJS is fully written in TypeScript. Would you mind to write TypeScript declarations?

Is this project still active/maintained?

There seems a steep drop off in activity as of late and open issues that seem a bit stale. Just curious as to how likely I would be to get help if I ended up using your seemingly wonderful library.

Linter

I wanted to add some linting to the project, any suggestion/preferences? (my +1 goes for standard)

relative preset "es2015" not found with create-react-native-app

When using this with create-react-native-app, I get some sort of TransformError. The error says that a "es2015" preset is not found relative to node_modules/redux-cycles/dist/index.js. I checked the package.json of this package and the babel configs are there. So I'm a bit unsure if the error is with the library or create-react-native-app.

ATM, I can get it to work by manually entering node_modules/redux-cycles/ and doing two things:

  1. install deps: yarn install
  2. adding a .babelrc that contains the preset "es2015"

What are the $s in variable names?

As a n00b to this library and observables, it's not clear why a lot of the variables in the README's examples have dollar signs at the end of their names.

Explaining the convention would make your project more accessible.

(Following the links to other libraries cited is not helpful either: the first code examples given in the docs for both Cycle.js and redux-observable also introduce dollar-sign variables with no explanation.)

Getting odd behaviour when using STATE

@goshakkk so I'm trying out your STATE extension but getting some odd behaviour: https://jsbin.com/kijucaw/6/edit?js,output

Try clicking the "odd +" button which triggers a read to the STATE stream. It doesn't work as expected and if you click it multiple times you get a Maximum call stack size exceeded error. I'll be looking into a fix for this.

I was thinking that perhaps rather than a STATE stream we could do it the way redux-observable does: pass in the store reference down the ACTION stream somehow, so we can call store.getState() inside the stream composition whenever it is needed.

scheduleMicrotask is not a function

Hi guys
I upgraded to the latest version of @cycle/run and I'm getting schedulemicrotask is not a function
It doesn't happen with version "^3.0.0"

These are my dependencies:
screen shot 2017-12-27 at 14 44 46

This is the error:
screen shot 2017-12-27 at 14 45 28

Example failing tests

@nickbalestra can you try running npm i and npm run test on the example folder (with a clean install). I'm getting a weird Error: Cannot find module '@cycle/time' error and can't figure out why since @cycle/time is right there in package.json :(

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.