Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created October 5, 2018 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/c4c57f5ed2dbcd49b55dab7a2a641b74 to your computer and use it in GitHub Desktop.
Save ryanflorence/c4c57f5ed2dbcd49b55dab7a2a641b74 to your computer and use it in GitHub Desktop.
/////////////////////////////////////////////
// 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