├── .gitignore
├── .npmignore
├── .travis.yml
├── LICENSE
├── README.md
├── example
├── .babelrc
├── ActionTypes.js
├── README.md
├── actions
│ └── index.js
├── components
│ ├── Repos.jsx
│ ├── UserSearchInput.jsx
│ └── UserSearchResults.jsx
├── configureStore.js
├── containers
│ ├── Admin.jsx
│ ├── App.jsx
│ ├── ReposByUser.jsx
│ └── UserSearch.jsx
├── cycle
│ ├── index.js
│ └── test
│ │ ├── helpers.js
│ │ └── test.js
├── index.html
├── index.js
├── package.json
├── reducers
│ ├── adminAccess.js
│ ├── index.js
│ ├── reposByUser.js
│ ├── searchInFlight.js
│ └── userResults.js
└── webpack.config.js
├── index.d.ts
├── logo.png
├── package.json
├── src
├── combineCycles.js
├── createCycleMiddleware.js
└── index.js
└── test
└── createCycleMiddleware.test.js
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .babelrc
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 'node'
4 | script: npm install && npm test && cd example && npm install && npm test
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Luca Matteis
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Redux-cycles
2 |
3 |
4 |
5 |
6 |
7 | Handle redux async actions using [Cycle.js](https://cycle.js.org/).
8 |
9 | [](https://travis-ci.org/cyclejs-community/redux-cycles)
10 |
11 | ### Table of Contents
12 |
13 | * [Install](#install)
14 | * [Example](#example)
15 | * [Why?](#why)
16 | * [I already know Redux-thunk](#i-already-know-redux-thunk)
17 | * [I already know Redux-saga](#i-already-know-redux-saga)
18 | * [I already know Redux-observable](#i-already-know-redux-observable)
19 | * [Do I have to buy all-in?](#do-i-have-to-buy-all-in)
20 | * [What's this Cycle thing anyway?](#whats-this-cycle-thing-anyway)
21 | * [What does this look like?](#what-does-this-look-like)
22 | * [Drivers](#drivers)
23 | * [Utils](#utils)
24 | * [`combineCycles`](#combinecycles)
25 | * [Testing](#testing)
26 | * [Why not just use Cycle.js?](#why-not-just-use-cyclejs)
27 | * What's the difference between "adding Redux to Cycle.js" and "adding Cycle.js to Redux"?
28 |
29 | ## Install
30 |
31 | `npm install --save redux-cycles`
32 |
33 | 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`).
34 |
35 | ```js
36 | import { run } from '@cycle/run';
37 | import { createCycleMiddleware } from 'redux-cycles';
38 |
39 | function main(sources) {
40 | const pong$ = sources.ACTION
41 | .filter(action => action.type === 'PING')
42 | .mapTo({ type: 'PONG' });
43 |
44 | return {
45 | ACTION: pong$
46 | }
47 | }
48 |
49 | const cycleMiddleware = createCycleMiddleware();
50 | const { makeActionDriver } = cycleMiddleware;
51 |
52 | const store = createStore(
53 | rootReducer,
54 | applyMiddleware(cycleMiddleware)
55 | );
56 |
57 | run(main, {
58 | ACTION: makeActionDriver()
59 | })
60 | ```
61 |
62 | By default `@cycle/run` uses `xstream`. If you want to use another streaming library simply import it and use its `run` method instead.
63 |
64 | For RxJS:
65 |
66 | ```js
67 | import { run } from '@cycle/rxjs-run';
68 | ```
69 |
70 | For Most.js:
71 |
72 | ```js
73 | import { run } from '@cycle/most-run';
74 | ```
75 |
76 |
77 | ## Example
78 |
79 | Try out this [JS Bin](https://jsbin.com/bomugapuxi/2/edit?js,output).
80 |
81 | See a real world example: [cycle autocomplete](https://github.com/cyclejs-community/redux-cycles/blob/master/example/cycle/index.js).
82 |
83 | ## Why?
84 |
85 | There already are several side-effects solutions in the Redux ecosystem:
86 |
87 | * [redux-thunk](https://github.com/gaearon/redux-thunk)
88 | * [redux-saga](https://github.com/redux-saga/redux-saga)
89 | * [redux-ship](https://clarus.github.io/redux-ship/)
90 | * [redux-observable](http://redux-observable.js.org)
91 |
92 | Why create yet another one?
93 |
94 | The intention with redux-cycles was not to worsen the "JavaScript fatigue".
95 | Rather it provides a solution that solves several problems attributable to the currently available libraries.
96 |
97 | * **Respond to actions as they happen, from the side.**
98 |
99 | Redux-thunk forces you to put your logic directly into the action creator.
100 | This means that all the logic caused by a particular action is located in one place... which doesn't do the readability a favor.
101 | It also means cross-cutting concerns like analytics get spread out across many files and functions.
102 |
103 | 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.
104 |
105 | * **Declarative side-effects.**
106 |
107 | For several reasons: code clarity and testability.
108 |
109 | With redux-thunk and redux-observable you just smash everything together.
110 |
111 | Redux-saga does make testing easier to an extent, but side-effects are still ad-hoc.
112 |
113 | Redux-cycles, powered by Cycle.js, introduces an abstraction for reaching into the real world in an explicit manner.
114 |
115 | * **Statically typable.**
116 |
117 | Because static typing helps you catch several types of mistakes early on.
118 | It also allows you to model data and relationships in your program upfront.
119 |
120 | Redux-saga falls short in the typing department... but it's not its fault entirely.
121 | 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.
122 |
123 | Observables, on the other hand, are easier to type.
124 |
125 | ### I already know Redux-thunk
126 |
127 | If you already know Redux-thunk, but find it limiting or clunky, Redux-cycles can help you to:
128 |
129 | * Move business logic out of action creators, leaving them pure and simple.
130 |
131 | You don't necessarily need Redux-cycles if your goal is only that.
132 | You might find Redux-saga to be easier to switch to.
133 |
134 | ### I already know Redux-saga
135 |
136 | Redux-cycles can help you to:
137 |
138 | * Handle your side-effects declaratively.
139 |
140 | Side-effect handling in Redux-saga makes testing easier compared to thunks, but you're still ultimately doing glorified function calls.
141 | The Cycle.js architecture pushes side-effect handling further to the edges of your application, leaving your "cycles" operate on pure streams.
142 |
143 | * Type your business logic.
144 |
145 | Most of your business logic lives in sagas... and they are hard/impossible to statically type.
146 | Have you had silly bugs in your sagas that Flow could have caught?
147 | I sure had.
148 |
149 | ### I already know Redux-observable
150 |
151 | Redux-cycles appears to be similar to Redux-observable... which it is, due to embracing observables.
152 | So why might you want to try Redux-cycles?
153 |
154 | In a word: easier side-effect handling.
155 | With Redux-observable your side-effectful code is scattered through all your epics, *directly*.
156 |
157 | It's hard to test.
158 | The code is less legible.
159 |
160 | ### Do I have to buy all-in?
161 |
162 | Should you go ahead and rewrite the entirety of your application in Redux-cycles to take advantage of it?
163 |
164 | **Not at all.**
165 |
166 | It's not the best strategy really.
167 | 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.
168 |
169 | A great example of a small category like that could be:
170 |
171 | * local storage calls
172 | * payments API
173 |
174 | The domain API layer often is not the easiest one to switch, so if you're thinking that... think of something smaller :)
175 |
176 | **Redux-saga** can still be valuable, even if using Redux-cycles.
177 | Certain sagas read crystal clear; sagas that orchestrate user flow.
178 |
179 | Like onboarding maybe: after the user signs up, and adds two todos, show a "keep going!" popup.
180 |
181 | This kind of logic fits the imperative sagas model *perfectly*, and it will likely look more cryptic if you try to redo it reactively.
182 |
183 | Life's not all-or-nothing, you can definitely use Redux-cycles and Redux-saga side-by-side.
184 |
185 | ## What's this Cycle thing anyway?
186 |
187 | [Cycle.js](https://cycle.js.org) is an interesting and unusual way of representing real-world programs.
188 |
189 | 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.
190 |
191 |
192 |
stream
193 |
is like an asynchronous, always-changing array of values
194 |
source
195 |
is a stream of real-world events as they happen
196 |
sink
197 |
is a stream of commands to be performed
198 |
a cycle (not to be confused with Cycle.js the library)
199 |
is a building block of Cycle.js, a function which takes sources (at least ACTION and STATE), and returns sinks
200 |
201 |
202 | Redux-cycles provides an `ACTION` source, which is a stream of Redux actions, and listens to the `ACTION` sink.
203 |
204 | ```javascript
205 | function main(sources) {
206 | const pong$ = sources.ACTION
207 | .filter(action => action.type === 'PING')
208 | .mapTo({ type: 'PONG' });
209 |
210 | return {
211 | ACTION: pong$
212 | }
213 | }
214 | ```
215 |
216 | Custom side-effects are handled similarly — by providing a different source and listening to a different sink.
217 | An example with HTTP requests will be shown later in this readme.
218 |
219 | 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.
220 | With Redux-cycles, you are effectively using Cycle only for side-effect management, leaving the view to React, and the state to Redux.
221 |
222 | ## What does this look like?
223 |
224 | Here's how Async is done using [redux-observable](https://github.com/redux-observable/redux-observable).
225 | The problem is that we still have side-effects in our epics (`ajax.getJSON`).
226 | This means that we're still writing imperative code:
227 |
228 | ```js
229 | const fetchUserEpic = action$ =>
230 | action$.ofType(FETCH_USER)
231 | .mergeMap(action =>
232 | ajax.getJSON(`https://api.github.com/users/${action.payload}`)
233 | .map(fetchUserFulfilled)
234 | );
235 | ```
236 |
237 | With Cycle.js we can push them even further outside our app using drivers, allowing us to write entirely declarative code:
238 |
239 | ```js
240 | function main(sources) {
241 | const request$ = sources.ACTION
242 | .filter(action => action.type === FETCH_USER)
243 | .map(action => ({
244 | url: `https://api.github.com/users/${action.payload}`,
245 | category: 'users',
246 | }));
247 |
248 | const action$ = sources.HTTP
249 | .select('users')
250 | .flatten()
251 | .map(fetchUserFulfilled);
252 |
253 | return {
254 | ACTION: action$,
255 | HTTP: request$
256 | };
257 | }
258 | ```
259 |
260 | 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](https://github.com/redux-observable/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.
261 |
262 | ## Drivers
263 |
264 | Redux-cycles ships with two drivers:
265 |
266 | * `makeActionDriver()`, which is a read-write driver, allowing to react to actions that have just happened, as well as to dispatch new actions.
267 | * `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.
268 |
269 | ```javascript
270 | import sampleCombine from 'xstream/extra/sampleCombine'
271 |
272 | function main(sources) {
273 | const state$ = sources.STATE;
274 | const isOdd$ = state$.map(state => state.counter % 2 === 0);
275 | const increment$ = sources.ACTION
276 | .filter(action => action.type === INCREMENT_IF_ODD)
277 | .compose(sampleCombine(isOdd$))
278 | .map(([ action, isOdd ]) => isOdd ? increment() : null)
279 | .filter(action => action);
280 |
281 | return {
282 | ACTION: increment$
283 | };
284 | }
285 | ```
286 |
287 | Here's an example on [how the STATE driver works](https://jsbin.com/rohomaxuma/2/edit?js,output).
288 |
289 | ## Utils
290 |
291 | ### `combineCycles`
292 |
293 | 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.
294 |
295 | **Example**:
296 |
297 | ```javascript
298 | import { combineCycles } from 'redux-cycles';
299 |
300 | // import all your cycle apps (main functions) you intend to use with the middleware:
301 | import fetchReposByUser from './fetchReposByUser';
302 | import searchUsers from './searchUsers';
303 | import clearSearchResults from './clearSearchResults';
304 |
305 | export default combineCycles(
306 | fetchReposByUser,
307 | searchUsers,
308 | clearSearchResults
309 | );
310 |
311 | ```
312 |
313 | You can see it used in the provided [example](https://github.com/cyclejs-community/redux-cycles/blob/master/example/cycle/index.js).
314 |
315 | ## Testing
316 |
317 | 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](https://github.com/cyclejs-community/redux-cycles/blob/master/example/cycle/test/test.js). Also checkout the [cyclejs/time](https://github.com/cyclejs/time) project, which should work perfectly with redux-cycles.
318 |
319 | ## Why not just use Cycle.js?
320 |
321 | 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.
322 |
323 | ### What's the difference between "adding Redux to Cycle.js" and "adding Cycle.js to Redux"?
324 |
325 | 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.
326 |
327 | 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.
328 |
--------------------------------------------------------------------------------
/example/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [ "es2015" ]
3 | }
4 |
--------------------------------------------------------------------------------
/example/ActionTypes.js:
--------------------------------------------------------------------------------
1 | export const SEARCHED_USERS = 'SEARCHED_USERS';
2 | export const RECEIVED_USERS = 'RECEIVED_USERS';
3 | export const CLEARED_SEARCH_RESULTS = 'CLEARED_SEARCH_RESULTS';
4 |
5 | export const REQUESTED_USER_REPOS = 'REQUESTED_USER_REPOS';
6 | export const RECEIVED_USER_REPOS = 'RECEIVED_USER_REPOS';
7 |
8 | export const CHECKED_ADMIN_ACCESS = 'CHECKED_ADMIN_ACCESS';
9 | export const ACCESS_DENIED = 'ACCESS_DENIED';
10 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | ```
2 | npm install
3 | npm run serve
4 | ```
5 |
--------------------------------------------------------------------------------
/example/actions/index.js:
--------------------------------------------------------------------------------
1 | import * as ActionTypes from '../ActionTypes';
2 |
3 | export function searchUsers(query) {
4 | return {
5 | type: ActionTypes.SEARCHED_USERS,
6 | payload: {
7 | query
8 | }
9 | };
10 | }
11 |
12 | export function receiveUsers(users) {
13 | return {
14 | type: ActionTypes.RECEIVED_USERS,
15 | payload: {
16 | users
17 | }
18 | };
19 | }
20 |
21 | export function clearSearchResults() {
22 | return {
23 | type: ActionTypes.CLEARED_SEARCH_RESULTS
24 | };
25 | }
26 |
27 | export function requestReposByUser(user) {
28 | return {
29 | type: ActionTypes.REQUESTED_USER_REPOS,
30 | payload: {
31 | user
32 | }
33 | };
34 | }
35 |
36 | export function receiveUserRepos(user, repos) {
37 | return {
38 | type: ActionTypes.RECEIVED_USER_REPOS,
39 | payload: {
40 | user,
41 | repos
42 | }
43 | };
44 | }
45 |
46 | export function checkAdminAccess() {
47 | return {
48 | type: ActionTypes.CHECKED_ADMIN_ACCESS
49 | };
50 | }
51 |
52 | export function accessDenied() {
53 | return {
54 | type: ActionTypes.ACCESS_DENIED
55 | };
56 | }
57 |
--------------------------------------------------------------------------------
/example/components/Repos.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | export default function Repos({ repos, user }) {
4 | return (
5 |