'use strict';
import { h, render, Component } from 'preact';
import * as numbers from '../lib/numbers.js';
import Client from '../lib/client.js';
const dayInSeconds = 60 * 60 * 24;
class Table extends Component {
constructor(props) {
super(props)
this.state = {
records: [],
limit: 5,
loading: true
}
this.tableHeaders = props.headers.map(heading =>
{heading} | )
this.fetchRecords = this.fetchRecords.bind(this)
this.handleLimitChoice = this.handleLimitChoice.bind(this)
}
componentDidMount() {
this.fetchRecords(this.props.period, this.state.limit)
}
labelCell(p) {
if( this.props.labelCell ) {
return this.props.labelCell(p)
}
return (
{p.Label.substring(0, 15)} |
)
}
componentWillReceiveProps(newProps) {
if(this.props.period != newProps.period) {
this.fetchRecords(newProps.period, this.state.limit)
}
}
handleLimitChoice(e) {
this.setState({ limit: parseInt(e.target.value) })
this.fetchRecords(this.props.period, this.state.limit)
}
fetchRecords(period, limit) {
this.setState({ loading: true });
const before = Math.round((+new Date() ) / 1000);
const after = before - ( period * dayInSeconds );
Client.request(`${this.props.endpoint}?before=${before}&after=${after}&limit=${limit}`)
.then((d) => {
this.setState({ loading: false, records: d }
)}).catch((e) => { console.log(e) })
}
render() {
const tableRows = this.state.records.map((p, i) => (
{i+1} |
{this.labelCell(p)}
{numbers.formatWithComma(p.Value)} |
{Math.round(p.PercentageValue)}% |
));
const loadingOverlay = this.state.loading ? : '';
return (
{loadingOverlay}
{this.props.title}
{this.tableHeaders}
{tableRows}
)
}
}
export default Table