BlocksContainer.js
1 import React, {Component} from 'react'; 2 import {connect} from 'react-redux'; 3 import PropTypes from 'prop-types'; 4 5 import {blocks as blocksAction, initBlockHeader, stopBlockHeader} from '../actions'; 6 import Blocks from '../components/Blocks'; 7 import DataWrapper from "../components/DataWrapper"; 8 import {getBlocks} from "../reducers/selectors"; 9 10 const MAX_BLOCKS = 10; // TODO use same constant as API 11 12 class BlocksContainer extends Component { 13 constructor(props) { 14 super(props); 15 16 this.state = {currentPage: 0}; 17 this.numberOfBlocks = 0; 18 this.currentBlocks = []; 19 } 20 21 componentDidMount() { 22 this.props.fetchBlocks(); 23 this.props.initBlockHeader(); 24 } 25 26 componentWillUnmount() { 27 this.props.stopBlockHeader(); 28 } 29 30 getNumberOfPages() { 31 if (!this.numberOfBlocks) { 32 let blocks = this.props.blocks; 33 if (blocks.length === 0) { 34 this.numberOfBlocks = 0; 35 } else { 36 this.numberOfBlocks = blocks[blocks.length - 1].number - 1; 37 } 38 } 39 return Math.ceil(this.numberOfBlocks / MAX_BLOCKS); 40 } 41 42 changePage(newPage) { 43 this.setState({currentPage: newPage}); 44 45 this.props.fetchBlocks((newPage * MAX_BLOCKS) + MAX_BLOCKS); 46 } 47 48 getCurrentBlocks() { 49 const currentPage = this.state.currentPage || this.getNumberOfPages(); 50 return this.props.blocks.filter(block => block.number <= (currentPage * MAX_BLOCKS) + MAX_BLOCKS && 51 block.number > currentPage * MAX_BLOCKS); 52 } 53 54 render() { 55 const newBlocks = this.getCurrentBlocks(); 56 if (newBlocks.length) { 57 this.currentBlocks = newBlocks; 58 } 59 return ( 60 <React.Fragment> 61 <DataWrapper shouldRender={this.currentBlocks.length > 0} {...this.props} render={() => ( 62 <Blocks blocks={this.currentBlocks} numberOfPages={this.getNumberOfPages()} 63 changePage={(newPage) => this.changePage(newPage)} 64 currentPage={this.state.currentPage || this.getNumberOfPages()} /> 65 )} /> 66 </React.Fragment> 67 ); 68 } 69 } 70 71 function mapStateToProps(state) { 72 return {blocks: getBlocks(state), error: state.errorMessage, loading: state.loading}; 73 } 74 75 BlocksContainer.propTypes = { 76 blocks: PropTypes.arrayOf(PropTypes.object), 77 fetchBlocks: PropTypes.func, 78 initBlockHeader: PropTypes.func, 79 stopBlockHeader: PropTypes.func, 80 error: PropTypes.string, 81 loading: PropTypes.bool 82 }; 83 84 export default connect( 85 mapStateToProps, 86 { 87 fetchBlocks: blocksAction.request, 88 initBlockHeader, 89 stopBlockHeader 90 }, 91 )(BlocksContainer);