Skip to content

Instantly share code, notes, and snippets.

@ryanflorence

ryanflorence/block4.jsx Secret

Created Oct 5, 2018
Embed
What would you like to do?
/////////////////////////////////////////////
// the store and reducer
import { createStore } from 'redux'
import { connect } from 'react-redux'
let reducer = (state, action) => {
if (action.type === 'LOADED_INVOICE') {
return {
...state,
invoice: action.data
}
}
return state
}
let store = createStore(reducer)
/////////////////////////////////////////////
// the action
function fetchInvoice(dispatch, id) {
fetch(`/invoices/${id}`).then(response => {
dispatch({
type: 'LOADED_INVOICE',
data: response.json()
})
})
}
/////////////////////////////////////////////
// the component, all connected up
class Invoice extends React.Component {
componentDidMount() {
fetchInvoice(this.props.dispatch, this.props.invoiceId)
}
componentDidUpdate(prevProps) {
if (prevProps.invoiceId !== this.props.invoiceId) {
fetchInvoice(this.props.dispatch, this.props.invoiceId)
}
}
render() {
if (!this.props.invoice) {
return null
}
return <h1>{invoice.number}</h1>
}
}
export default connect(state => {
return { invoices: state.invoices }
})(Invoices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.