-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathcalculator-tiles.js
64 lines (57 loc) · 1.99 KB
/
calculator-tiles.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { createTile, createSyncTile } from 'redux-tiles';
// we want to use `params` variable from `fn` as a returning value
// so we can omit `fn` at all – it is a default behaviour!
const currentValuesTile = createSyncTile({
type: ['calculator', 'values', 'current'],
initialState: { value: 10 }
});
const nextValuesTile = createSyncTile({
type: ['calculator', 'values', 'next'],
});
// this is an api call tile
// note how isolated it is – it's only responsibility
// is to call api and to store this info, along with caching
const calculateOfferRequest = createTile({
type: ['api', 'offer'],
fn: ({ api, params }) => api.get('/offer', params),
// nesting can be more complicated, than just list of params
nesting: ({ value }) => {
if (!value) {
return ['default'];
}
return [value];
},
caching: true,
});
// this is a "business logic" tile
// it updates future values
// make an api call for offer
// and changes current values, if there is
// no race condition
const calculateOffer = createTile({
type: ['calculator', 'calculateOffer'],
fn: async ({ params, dispatch, actions, selectors, getState }) => {
// set nextValues
dispatch(actions.calculator.values.next(params));
// calculate new offer
await dispatch(actions.api.offer(params));
// get next params, and if they are the same, change current
// we have to do it, because another request might come, and
// then we could introduce race condition
const nextValues = selectors.calculator.values.next(getState());
if (nextValues.value === params.value) {
// after this dispatch we'll re-render offer
dispatch(actions.calculator.values.current(params));
}
// we don't really have to return anything; we just want to dispatch
// actions from this tile
// but if you want, it is possible to add meaningful resolving params
// and nesting for separation
},
});
export default [
currentValuesTile,
nextValuesTile,
calculateOfferRequest,
calculateOffer
];