Created
July 1, 2019 22:24
-
-
Save zsajjad/c40ed0ac14c36f11f01ef1864ae1d9e7 to your computer and use it in GitHub Desktop.
Class based Container with children props
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
/* | |
* | |
* HackerNews | |
* | |
*/ | |
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { connect } from 'react-redux'; | |
import { createStructuredSelector } from 'reselect'; | |
import { compose } from 'redux'; | |
import injectReducer from 'utils/injectReducer'; | |
import injectSaga from 'utils/injectSaga'; | |
import reducer from './reducer'; | |
import saga from './sagas'; | |
import makeSelectHackerNews from './selectors'; | |
import { fetch } from './actions'; | |
class HackerNews extends React.PureComponent { | |
componentDidMount() { | |
const { hackerNews } = this.props; | |
if (!hackerNews.data.length && !hackerNews.fetching) { | |
this.props.fetch({ | |
offset: 0, | |
limit: 15, | |
}); | |
} | |
} | |
render() { | |
const { fetching, data, error } = this.props.hackerNews; | |
return this.props.children.call(null, { | |
fetching, | |
data, | |
error, | |
}); | |
} | |
} | |
HackerNews.propTypes = { | |
hackerNews: PropTypes.object.isRequired, | |
children: PropTypes.func.isRequired, | |
fetch: PropTypes.func.isRequired, | |
}; | |
const mapStateToProps = createStructuredSelector({ | |
hackerNews: makeSelectHackerNews(), | |
}); | |
function mapDispatchToProps(dispatch) { | |
return { | |
fetch: (data) => dispatch(fetch(data)), | |
}; | |
} | |
const withConnect = connect( | |
mapStateToProps, | |
mapDispatchToProps, | |
); | |
const withReducer = injectReducer({ key: 'hackerNews', reducer }); | |
const withSaga = injectSaga({ key: 'hackerNews', saga }); | |
export default compose( | |
withReducer, | |
withSaga, | |
withConnect, | |
)(HackerNews); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment