xonecas.io
3517
Mt

meal_tracker / files

meal_tracker / bmi_ui / src / components / MealsTable.js

2.4 KB
1import React, { Component } from 'react'
2import PropTypes from 'prop-types'
3import { Table, Button } from 'reactstrap'
4import MealModal from './MealModal'
5import axios from 'axios'
6import { API_URL } from '../constants'
7
8class MealsTable extends Component {
9  static get propTypes () {
10    return {
11      create: PropTypes.boolean,
12      meals: PropTypes.any,
13      user: PropTypes.any,
14      toggle: PropTypes.func,
15      update: PropTypes.func
16    }
17  }
18
19  delete (e, value) {
20    e && e.preventDefault()
21
22    const mealId = e.currentTarget.getAttribute('data-meal-id')
23
24    axios.delete(API_URL + 'meals/' + mealId + '/', {
25      crossdomain: true,
26      headers: { Authorization: 'Token ' + this.props.user.token }
27    }).then((response) => {
28      this.props.update()
29    })
30  }
31
32  render () {
33    const mealsGroupedByDay = {}
34
35    this.props.meals.forEach((m, i) => {
36      mealsGroupedByDay[m.date] = mealsGroupedByDay[m.date] || 0
37      mealsGroupedByDay[m.date] += m.calories
38    })
39
40    this.props.meals.forEach((m) => {
41      if (mealsGroupedByDay[m.date] > this.props.user.preferences.max_calories) {
42        m.color = 'pt-3 text-danger'
43      } else {
44        m.color = 'pt-3 text-success'
45      }
46    })
47
48    return (
49      <Table>
50        <thead>
51          <tr>
52            <th>#</th>
53            <th>Title</th>
54            <th>Calories</th>
55            <th>Date</th>
56            <th>Time</th>
57            <th></th>
58          </tr>
59        </thead>
60        <tbody>
61          {this.props.meals.map((m, i) =>
62            <tr key={i}>
63              <th scope='row' className='pt-3'>{i + 1}</th>
64              <th className={m.color}>{m.text}</th>
65              <th className={m.color}>{m.calories}</th>
66              <th className={m.color}>{m.date}</th>
67              <th className={m.color}>{m.time}</th>
68              <th className='no-pad-right'>
69                <MealModal
70                  meal={m}
71                  user={this.props.user}
72                  update={this.props.update}
73                />
74                <Button
75                  color='danger'
76                  outline
77                  data-meal-id={m.id}
78                  onClick={this.delete.bind(this)}
79                  size='sm'
80                  className='mr-2 float-right'
81                >Delete</Button>
82              </th>
83            </tr>
84          )}
85        </tbody>
86      </Table>
87    )
88  }
89}
90
91export default MealsTable