Created
April 21, 2018 18:27
-
-
Save peerreynders/f954ced724049f545d9056a861cdc911 to your computer and use it in GitHub Desktop.
RxJS in Action Ch10 1A: 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) | |
// | |
// $ create-react-app in-the-wild | |
// $ cd in-the-wild | |
// $ npm i -P rxjs | |
// $ npm start | |
import React, {Component} from 'react'; | |
import ReactDOM from 'react-dom'; | |
import registerServiceWorker from './registerServiceWorker'; | |
import Rx from 'rxjs'; | |
const locale = 'en-US'; | |
const currency = 'USD'; | |
const balanceFormat = | |
new Intl.NumberFormat(locale, {style: 'currency', currency}); | |
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 {state: {checking, savings}} = this; | |
const checkingAmount = balanceFormat.format(checking); | |
const savingsAmount = balanceFormat.format(savings); | |
return <div>Checking: {checkingAmount} Savings {savingsAmount}</div>; | |
} | |
} | |
// --- Listing 10.1 end | |
ReactDOM.render( | |
<Balances />, | |
document.getElementById('root') | |
); | |
registerServiceWorker(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment