TransactionsContainer.js
1 import React, {Component} from 'react'; 2 import {connect} from 'react-redux'; 3 import PropTypes from 'prop-types'; 4 5 import {transactions as transactionsAction, initBlockHeader, stopBlockHeader} from '../actions'; 6 import Transactions from '../components/Transactions'; 7 import DataWrapper from "../components/DataWrapper"; 8 import {getTransactions} from "../reducers/selectors"; 9 10 const MAX_TXS = 10; // TODO use same constant as API 11 12 class TransactionsContainer extends Component { 13 constructor(props) { 14 super(props); 15 16 this.state = {currentPage: 0}; 17 this.numberOfTxs = 0; 18 this.currentTxs = []; 19 } 20 21 componentDidMount() { 22 this.props.fetchTransactions(); 23 this.props.initBlockHeader(); 24 } 25 26 componentWillUnmount() { 27 this.props.stopBlockHeader(); 28 } 29 30 getNumberOfPages() { 31 if (!this.numberOfTxs) { 32 let transactions = this.props.transactions; 33 if (transactions.length === 0) { 34 this.numberOfTxs = 0; 35 } else { 36 this.numberOfTxs = transactions[transactions.length - 1].blockNumber - 1; 37 } 38 } 39 return Math.ceil(this.numberOfTxs / MAX_TXS); 40 } 41 42 changePage(newPage) { 43 this.setState({currentPage: newPage}); 44 45 this.props.fetchTransactions((newPage * MAX_TXS) + MAX_TXS); 46 } 47 48 getCurrentTransactions() { 49 const currentPage = this.state.currentPage || this.getNumberOfPages(); 50 return this.props.transactions.filter(tx => tx.blockNumber <= (currentPage * MAX_TXS) + MAX_TXS && 51 tx.blockNumber > currentPage * MAX_TXS); 52 } 53 54 render() { 55 const newTxs = this.getCurrentTransactions(); 56 if (newTxs.length) { 57 this.currentTxs = newTxs; 58 } 59 return ( 60 <React.Fragment> 61 <DataWrapper shouldRender={this.currentTxs.length > 0} {...this.props} render={() => ( 62 <Transactions transactions={this.currentTxs} 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 {transactions: getTransactions(state), error: state.errorMessage, loading: state.loading}; 73 } 74 75 TransactionsContainer.propTypes = { 76 transactions: PropTypes.arrayOf(PropTypes.object), 77 fetchTransactions: 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 fetchTransactions: transactionsAction.request, 88 initBlockHeader, 89 stopBlockHeader 90 }, 91 )(TransactionsContainer);