├── .babelrc
├── .editorconfig
├── .gitignore
├── .npmignore
├── .travis.yml
├── README.md
├── UPGRADE_GUIDE.md
├── package.json
├── src
├── index.js
├── propName.js
├── provideHooks.js
└── trigger.js
└── test
├── index.js
└── mocha.opts
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "optional": [
3 | "es7.decorators"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 | root = true
3 |
4 | [*]
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | charset = utf-8
9 | trim_trailing_whitespace = true
10 | insert_final_newline = true
11 |
12 | [*.md]
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | lib
3 | coverage
4 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .babelrc
2 | src
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "4.1"
4 | after_script:
5 | - npm run coveralls
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](http://travis-ci.org/markdalgleish/redial) [](https://coveralls.io/r/markdalgleish/redial) [](https://www.npmjs.com/package/redial)
2 |
3 | # redial
4 |
5 | Universal data fetching and route lifecycle management for React etc.
6 |
7 | ```bash
8 | $ npm install --save redial
9 | ```
10 |
11 | ## Why?
12 |
13 | When using something like [React Router](https://github.com/rackt/react-router), you'll want to ensure that all data for a set of routes is prefetched on the server before attempting to render.
14 |
15 | However, as your application grows, you're likely to discover the need for more advanced route lifecycle management.
16 |
17 | For example, you might want to separate mandatory data dependencies from those that are allowed to fail. You might want to defer certain data fetching operations to the client, particularly in the interest of server-side performance. You might also want to dispatch page load events once all data fetching has completed on the client.
18 |
19 | In order to accommodate these scenarios, the ability to define and trigger your own custom route-level lifecycle hooks becomes incredibly important.
20 |
21 | ## Providing lifecycle hooks
22 |
23 | The `@provideHooks` decorator allows you to define hooks for your custom lifecycle events, returning promises if any asynchronous operations need to be performed. When using something like React Router, you'll want to decorate your route handlers rather than lower level components.
24 |
25 | For example:
26 |
27 | ```js
28 | import { provideHooks } from 'redial';
29 |
30 | import React, { Component } from 'react';
31 | import { getSomething, getSomethingElse, trackDone } from 'actions/things';
32 |
33 | @provideHooks({
34 | fetch: ({ dispatch, params: { id } }) => dispatch(getSomething(id)),
35 | defer: ({ dispatch, params: { id } }) => dispatch(getSomethingElse(id)),
36 | done: ({ dispatch }) => dispatch(trackDone())
37 | })
38 | class MyRouteHandler extends Component {
39 | render() {
40 | return
...
;
41 | }
42 | }
43 | ```
44 |
45 | If you'd prefer to avoid using decorators, you can use `provideHooks` as a plain old function:
46 |
47 | ```js
48 | const hooks = {
49 | fetch: ({ dispatch, params: { id } }) => dispatch(getSomething(id)),
50 | defer: ({ dispatch, params: { id } }) => dispatch(getSomethingElse(id)),
51 | done: ({ dispatch }) => dispatch(trackDone())
52 | };
53 |
54 | class MyRouteHandler extends Component {
55 | render() {
56 | return ...
;
57 | }
58 | }
59 |
60 | export default provideHooks(hooks)(MyRouteHandler);
61 | ```
62 |
63 | ### Triggering lifecycle events
64 |
65 | Once you've decorated your components, you can then use the `trigger` function to initiate an event for an arbitrary array of components, or even a single component if required. Since hooks tend to be asynchronous, this operation always returns a promise.
66 |
67 | For example, when fetching data before rendering on the server:
68 |
69 | ```js
70 | import { trigger } from 'redial';
71 |
72 | const locals = {
73 | some: 'data',
74 | more: 'stuff'
75 | };
76 |
77 | trigger('fetch', components, locals).then(render);
78 | ```
79 |
80 | ### Dynamic locals
81 |
82 | If you need to calculate different locals for each lifecycle hook, you can provide a function instead of an object. This function is then executed once per lifecycle hook, with a static reference to the component provided as an argument.
83 |
84 | For example, this would allow you to calculate whether a component is being rendered for the first time and pass the result in via the locals object:
85 |
86 | ```js
87 | const getLocals = component => ({
88 | isFirstRender: prevComponents.indexOf(component) === -1
89 | });
90 |
91 | trigger('fetch', components, getLocals).then(render);
92 | ```
93 |
94 | ## Example usage with React Router and Redux
95 |
96 | When [server rendering with React Router](https://github.com/rackt/react-router/blob/master/docs/guides/ServerRendering.md) (or using the same technique to render on the client), the `renderProps` object provided to the `match` callback has an array of routes, each of which has a component attached. You're also likely to want to pass some information from the router to your lifecycle hooks.
97 |
98 | In order to dispatch actions from within your hooks, you'll want to pass in a reference to your store's `dispatch` function. This works especially well with [redux-thunk](https://github.com/gaearon/redux-thunk) to ensure your async actions return promises.
99 |
100 | ### Example server usage
101 |
102 | ```js
103 | import { trigger } from 'redial';
104 |
105 | import React from 'react';
106 | import { renderToString } from 'react-dom/server';
107 | import { RouterContext, createMemoryHistory, match } from 'react-router';
108 | import { createStore, applyMiddleware } from 'redux';
109 | import { Provider } from 'react-redux';
110 | import thunk from 'redux-thunk';
111 |
112 | // Your app's reducer and routes:
113 | import reducer from './reducer';
114 | import routes from './routes';
115 |
116 | // Render the app server-side for a given path:
117 | export default path => new Promise((resolve, reject) => {
118 | // Set up Redux (note: this API requires redux@>=3.1.0):
119 | const store = createStore(reducer, applyMiddleware(thunk));
120 | const { dispatch, getState } = store;
121 |
122 | // Set up history for router:
123 | const history = createMemoryHistory(path);
124 |
125 | // Match routes based on history object:
126 | match({ routes, history }, (error, redirectLocation, renderProps) => {
127 | // Get array of route handler components:
128 | const { components } = renderProps;
129 |
130 | // Define locals to be provided to all lifecycle hooks:
131 | const locals = {
132 | path: renderProps.location.pathname,
133 | query: renderProps.location.query,
134 | params: renderProps.params,
135 |
136 | // Allow lifecycle hooks to dispatch Redux actions:
137 | dispatch
138 | };
139 |
140 | // Wait for async data fetching to complete, then render:
141 | trigger('fetch', components, locals)
142 | .then(() => {
143 | const state = getState();
144 | const html = renderToString(
145 |
146 |
147 |
148 | );
149 |
150 | resolve({ html, state });
151 | })
152 | .catch(reject);
153 | });
154 | });
155 | ```
156 |
157 | ### Example client usage
158 |
159 | ```js
160 | import { trigger } from 'redial';
161 |
162 | import React from 'react';
163 | import { render } from 'react-dom';
164 | import { Router, browserHistory, match } from 'react-router';
165 | import { createStore, applyMiddleware } from 'redux';
166 | import { Provider } from 'react-redux';
167 | import thunk from 'redux-thunk';
168 |
169 | // Your app's reducer and routes:
170 | import reducer from './reducer';
171 | import routes from './routes';
172 |
173 | // Render the app client-side to a given container element:
174 | export default container => {
175 | // Your server rendered response needs to expose the state of the store, e.g.
176 | //
179 | const initialState = window.INITIAL_STATE;
180 |
181 | // Set up Redux (note: this API requires redux@>=3.1.0):
182 | const store = createStore(reducer, initialState, applyMiddleware(thunk));
183 | const { dispatch } = store;
184 |
185 | // Listen for route changes on the browser history instance:
186 | browserHistory.listen(location => {
187 | // Match routes based on location object:
188 | match({ routes, location }, (error, redirectLocation, renderProps) => {
189 | // Get array of route handler components:
190 | const { components } = renderProps;
191 |
192 | // Define locals to be provided to all lifecycle hooks:
193 | const locals = {
194 | path: renderProps.location.pathname,
195 | query: renderProps.location.query,
196 | params: renderProps.params,
197 |
198 | // Allow lifecycle hooks to dispatch Redux actions:
199 | dispatch
200 | };
201 |
202 | // Don't fetch data for initial route, server has already done the work:
203 | if (window.INITIAL_STATE) {
204 | // Delete initial data so that subsequent data fetches can occur:
205 | delete window.INITIAL_STATE;
206 | } else {
207 | // Fetch mandatory data dependencies for 2nd route change onwards:
208 | trigger('fetch', components, locals);
209 | }
210 |
211 | // Fetch deferred, client-only data dependencies:
212 | trigger('defer', components, locals);
213 | });
214 | });
215 |
216 | // Render app with Redux and router context to container element:
217 | render((
218 |
219 |
220 |
221 | ), container);
222 | };
223 | ```
224 |
225 | ## Boilerplates using redial
226 |
227 | - [React Production Starter](https://github.com/jaredpalmer/react-production-starter) by [@jaredpalmer](https://twitter.com/jaredpalmer)
228 | - [Redux universal boilerplate](https://github.com/ufocoder/redux-universal-boilerplate) by [@xufocoder](https://twitter.com/xufocoder)
229 |
230 | ## Related projects
231 |
232 | - [React Resolver](https://github.com/ericclemmons/react-resolver) by [@ericclemmons](https://twitter.com/ericclemmons)
233 | - [React Transmit](https://github.com/RickWong/react-transmit) by [@rygu](https://twitter.com/rygu)
234 | - [AsyncProps for React Router](https://github.com/rackt/async-props) by [@ryanflorence](https://twitter.com/ryanflorence)
235 | - [GroundControl](https://github.com/raisemarketplace/ground-control) by [@nickdreckshage](https://twitter.com/nickdreckshage)
236 | - [React Async](https://github.com/andreypopp/react-async) by [@andreypopp](https://twitter.com/andreypopp)
237 |
238 | ## License
239 |
240 | [MIT License](http://markdalgleish.mit-license.org/)
241 |
--------------------------------------------------------------------------------
/UPGRADE_GUIDE.md:
--------------------------------------------------------------------------------
1 | # Upgrade Guide
2 |
3 | ## v0.4.0
4 |
5 | - The project was renamed from `react-fetcher` to `redial`.
6 |
7 | - `@prefetch` and `@defer` have been deprecated in favour of `@provideHooks`.
8 |
9 | ```diff
10 | -import { prefetch, defer } from 'react-fetcher';
11 | +import { provideHooks } from 'redial';
12 |
13 | -@prefetch(() => { ... })
14 | -@defer(() => { ... })
15 | +provideHooks({
16 | + fetch: () => { ... },
17 | + defer: () => { ... }
18 | +})
19 | class MyRouteHandler extends Component {
20 | ...
21 | }
22 | ```
23 |
24 | - `getPrefetchedData` and `getDeferredData` have been deprecated in favour of `trigger`.
25 |
26 | ```diff
27 | -import { getPrefetchedData, getDeferredData } from 'react-fetcher';
28 | +import { trigger } from 'redial';
29 |
30 | -getPrefetchedData(components, locals).then(() => { ... });
31 | +trigger('fetch', components, locals).then(() => { ... });
32 |
33 | -getDeferredData(components, locals).then(() => { ... });
34 | +trigger('defer', components, locals).then(() => { ... });
35 | ```
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "redial",
3 | "version": "0.5.0",
4 | "description": "Universal data fetching and route lifecycle management for React etc.",
5 | "main": "lib/index.js",
6 | "scripts": {
7 | "test": "babel-istanbul cover _mocha && babel-istanbul check-coverage --branches 100",
8 | "build": "rm -rf lib/ && ./node_modules/.bin/babel -d lib/ src/",
9 | "prepublish": "npm run build",
10 | "coveralls": "cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/markdalgleish/redial.git"
15 | },
16 | "author": "Mark Dalgleish",
17 | "license": "MIT",
18 | "bugs": {
19 | "url": "https://github.com/markdalgleish/redial/issues"
20 | },
21 | "homepage": "https://github.com/markdalgleish/redial#readme",
22 | "devDependencies": {
23 | "babel": "^5.8.23",
24 | "babel-istanbul": "^0.3.20",
25 | "chai": "^3.3.0",
26 | "coveralls": "^2.11.6",
27 | "mocha": "^2.3.3",
28 | "react": "^0.14.1",
29 | "sinon": "^1.17.1"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import provideHooks from './provideHooks';
2 | import trigger from './trigger';
3 |
4 | export default {
5 | provideHooks,
6 | trigger
7 | };
8 |
--------------------------------------------------------------------------------
/src/propName.js:
--------------------------------------------------------------------------------
1 | export default '@@redial-hooks';
2 |
--------------------------------------------------------------------------------
/src/provideHooks.js:
--------------------------------------------------------------------------------
1 | import propName from './propName';
2 |
3 | export default hooks => ComposedComponent => {
4 | ComposedComponent[propName] = hooks;
5 | return ComposedComponent;
6 | };
7 |
--------------------------------------------------------------------------------
/src/trigger.js:
--------------------------------------------------------------------------------
1 | import propName from './propName';
2 |
3 | export default (name, components, locals) => {
4 | const promises = (Array.isArray(components) ? components : [components])
5 |
6 | // Filter out falsy components
7 | .filter(component => component)
8 |
9 | // Get component lifecycle hooks
10 | .map(component => ({ component, hooks: component[propName] }))
11 |
12 | // Filter out components that haven't been decorated
13 | .filter(({ hooks }) => hooks)
14 |
15 | // Calculate locals if required, execute hooks and store promises
16 | .map(({ component, hooks }) => {
17 | const hook = hooks[name];
18 |
19 | if (typeof hook !== 'function') {
20 | return;
21 | }
22 |
23 | try {
24 | return typeof locals === 'function' ?
25 | hook(locals(component)) :
26 | hook(locals);
27 | } catch (err) {
28 | return Promise.reject(err);
29 | }
30 | });
31 |
32 | return Promise.all(promises);
33 | };
34 |
--------------------------------------------------------------------------------
/test/index.js:
--------------------------------------------------------------------------------
1 | import { assert } from 'chai';
2 | import { spy, stub } from 'sinon';
3 | import React, { Component } from 'react';
4 | import { provideHooks, trigger } from '../src';
5 |
6 | const makeTestObject = (hookName) => {
7 | let object = {};
8 |
9 | const prefetchPromise = new Promise((resolve, reject) => {
10 | object.resolve = resolve;
11 | object.reject = reject;
12 | });
13 | object.stub = stub().returns(prefetchPromise);
14 |
15 | @provideHooks({
16 | [hookName]: object.stub,
17 | throwError: () => {
18 | throw new Error('OHNOES');
19 | }
20 | })
21 | class TestComponent extends Component {
22 | render() { return ; }
23 | }
24 |
25 | object.component = TestComponent;
26 | return object;
27 | };
28 |
29 | describe('Given a series of components have been decorated with hooks', () => {
30 |
31 | let hook_a, hook_b;
32 |
33 | beforeEach(() => {
34 | hook_a = makeTestObject('foobar');
35 | hook_b = makeTestObject('foobar');
36 | });
37 |
38 | describe('When a handled lifecycle event is triggered', () => {
39 |
40 | let resolveSpy, rejectSpy;
41 |
42 | beforeEach(() => {
43 | const componentsWithFalsyValues = [
44 | undefined,
45 | hook_a.component,
46 | null,
47 | hook_b.component,
48 | false
49 | ];
50 |
51 | resolveSpy = spy();
52 | rejectSpy = spy();
53 |
54 | trigger('foobar', componentsWithFalsyValues, { some: 'data' })
55 | .then(resolveSpy, rejectSpy);
56 | });
57 |
58 | it('Then the hooks should have locals passed to them', () => {
59 | assert.deepEqual(hook_a.stub.getCall(0).args[0], { some: 'data' });
60 | assert.deepEqual(hook_b.stub.getCall(0).args[0], { some: 'data' });
61 | });
62 |
63 | describe('And the hook promises are resolved', () => {
64 |
65 | beforeEach(done => {
66 | hook_a.resolve();
67 | hook_b.resolve();
68 | setImmediate(done);
69 | });
70 |
71 | it('Then the lifecycle event promise should also be resolved', () => {
72 | assert.equal(resolveSpy.callCount, 1);
73 | assert.equal(rejectSpy.callCount, 0);
74 | });
75 |
76 | });
77 |
78 | describe('And a hook promise is rejected', () => {
79 |
80 | beforeEach(done => {
81 | hook_a.resolve();
82 | hook_b.reject();
83 | setImmediate(done);
84 | });
85 |
86 | it('Then the lifecycle event promise should also be rejected', () => {
87 | assert.equal(resolveSpy.callCount, 0);
88 | assert.equal(rejectSpy.callCount, 1);
89 | });
90 |
91 | });
92 |
93 | });
94 |
95 | describe('When a handled lifecycle event is triggered with a locals function', () => {
96 |
97 | let resolveSpy, rejectSpy;
98 |
99 | beforeEach(() => {
100 | resolveSpy = spy();
101 | rejectSpy = spy();
102 | let callCount = 0;
103 | const getLocals = component => ({ component, callCount: ++callCount });
104 | trigger('foobar', [ hook_a.component, hook_b.component ], getLocals)
105 | .then(resolveSpy, rejectSpy);
106 | });
107 |
108 | it('Then the hooks should have the correct locals passed to them', () => {
109 | assert.deepEqual(hook_a.stub.getCall(0).args[0], { component: hook_a.component, callCount: 1 });
110 | assert.deepEqual(hook_b.stub.getCall(0).args[0], { component: hook_b.component, callCount: 2 });
111 | });
112 |
113 | });
114 |
115 | describe('When a handled lifecycle event is triggered for a single component', () => {
116 |
117 | let resolveSpy, rejectSpy;
118 |
119 | beforeEach(() => {
120 | resolveSpy = spy();
121 | rejectSpy = spy();
122 | trigger('foobar', hook_a.component, { some: 'data' })
123 | .then(resolveSpy, rejectSpy);
124 | });
125 |
126 | it('Then the hook should have locals passed to it', () => {
127 | assert.deepEqual(hook_a.stub.getCall(0).args[0], { some: 'data' });
128 | });
129 |
130 | describe('And the hook promise is resolved', () => {
131 |
132 | beforeEach(done => {
133 | hook_a.resolve();
134 | setImmediate(done);
135 | });
136 |
137 | it('Then the lifecycle event promise should also be resolved', () => {
138 | assert.equal(resolveSpy.callCount, 1);
139 | assert.equal(rejectSpy.callCount, 0);
140 | });
141 |
142 | });
143 |
144 | });
145 |
146 | describe('When an unhandled lifecycle event is triggered for a single component', () => {
147 |
148 | let resolveSpy, rejectSpy;
149 |
150 | beforeEach(() => {
151 | resolveSpy = spy();
152 | rejectSpy = spy();
153 |
154 | return trigger('unhandled', hook_a.component, { some: 'data' })
155 | .then(resolveSpy, rejectSpy);
156 | });
157 |
158 | it('Then the lifecycle event promise should also be resolved', () => {
159 | assert.equal(resolveSpy.callCount, 1);
160 | assert.equal(rejectSpy.callCount, 0);
161 | });
162 |
163 | });
164 |
165 | describe('When a lifecycle event is triggered for a falsy value', () => {
166 |
167 | let resolveSpy, rejectSpy;
168 |
169 | beforeEach(() => {
170 | resolveSpy = spy();
171 | rejectSpy = spy();
172 |
173 | return trigger('unhandled', null, { some: 'data' })
174 | .then(resolveSpy, rejectSpy);
175 | });
176 |
177 | it('Then the lifecycle event promise should also be resolved', () => {
178 | assert.equal(resolveSpy.callCount, 1);
179 | assert.equal(rejectSpy.callCount, 0);
180 | });
181 |
182 | });
183 |
184 | describe('When a lifecycle hook throws an error', () => {
185 |
186 | let resolveSpy, rejectSpy;
187 |
188 | beforeEach(() => {
189 | resolveSpy = spy();
190 | rejectSpy = spy();
191 |
192 | return trigger('throwError', [ hook_a.component, hook_b.component ], {})
193 | .then(resolveSpy, rejectSpy);
194 | });
195 |
196 | it('Then the lifecycle event promise should be rejected', () => {
197 | assert.equal(resolveSpy.callCount, 0);
198 | assert.equal(rejectSpy.callCount, 1);
199 | assert.equal(rejectSpy.getCall(0).args[0].message, 'OHNOES');
200 | });
201 |
202 | });
203 |
204 | });
205 |
--------------------------------------------------------------------------------
/test/mocha.opts:
--------------------------------------------------------------------------------
1 | --compilers js:babel/register
2 |
--------------------------------------------------------------------------------