Created
April 21, 2018 18:31
-
-
Save peerreynders/4706f4ef0d72d4408234204149913e66 to your computer and use it in GitHub Desktop.
RxJS in Action Ch10 1B: A React account balances updates every second
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// file: src/index.js - Derived from: | |
// RxJS in Action (2017, Manning), 978-1-617-29341-2 | |
// by Paul P. Daniels and Luis Atencio | |
// Listing: | |
// 10.1 A React account balances updates every second (p.278) | |
// | |
// Variation B: | |
// - split BalancesView from Balances | |
// - pass BalancesView via render prop | |
import React, {Component} from 'react'; | |
import PropTypes from 'prop-types'; | |
import ReactDOM from 'react-dom'; | |
import registerServiceWorker from './registerServiceWorker'; | |
import Rx from 'rxjs'; | |
// Presentation Components | |
const locale = 'en-US'; | |
const currency = 'USD'; | |
const balanceFormat = | |
new Intl.NumberFormat(locale, {style: 'currency', currency}); | |
const AccountBalance = ({name, amount}) => | |
<div>{name}: {balanceFormat.format(amount)}</div>; | |
AccountBalance.propTypes = { | |
name : PropTypes.string, | |
amount : PropTypes.number | |
}; | |
const BalancesView =({checking, savings}) => | |
<div> | |
<AccountBalance {...{name: 'Checking', amount: checking}}/> | |
<AccountBalance {...{name: 'Savings', amount: savings}}/> | |
</div>; | |
BalancesView.propTypes = { | |
checking : PropTypes.number, | |
savings : PropTypes.number | |
}; | |
// Container Component | |
const initialState = () => ({ | |
checking: 0, | |
savings: 0 | |
}); | |
const setBalances = value => ({ | |
checking: value, | |
savings: value | |
}); | |
// --- Listing 10.1 A React account balances updates every second | |
class Balances extends Component { | |
constructor(props){ | |
super(props); | |
this.state = initialState(); | |
this.unsubscribe = null; | |
} | |
send = (state) => { | |
this.setState((_prevState, _props) => state); | |
} | |
componentDidMount() { | |
const { send } = this; | |
const subscription = | |
Rx.Observable | |
.interval(1000) | |
.map(setBalances) | |
.subscribe(send); | |
this.unsubscribe = () => subscription.unsubscribe(); | |
} | |
componentWillUnmount() { | |
const {unsubscribe} = this; | |
if(unsubscribe) { | |
unsubscribe(); | |
this.unsubscribe = null; | |
} | |
} | |
render() { | |
const {props: {render}, state: accounts} = this; | |
return render(accounts); | |
} | |
} | |
Balances.propTypes = { | |
render : PropTypes.func.isRequired | |
}; | |
// --- Listing 10.1 end | |
ReactDOM.render( | |
<Balances {...{render: BalancesView}}/>, | |
document.getElementById('root') | |
); | |
registerServiceWorker(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment