xonecas.io
3517
Mt

meal_tracker / files

meal_tracker / bmi_ui / src / components / MealForm.js

2.6 KB
1import React from 'react'
2import PropTypes from 'prop-types'
3import { Button, Form, FormGroup, Input, Label } from 'reactstrap'
4import axios from 'axios'
5import { API_URL } from '../constants'
6
7class MealForm extends React.Component {
8  constructor (props) {
9    super(props)
10
11    const meal = props.meal || {}
12
13    this.state = {
14      id: meal.id,
15      text: meal.text || '',
16      calories: meal.calories || 0,
17      date: meal.date,
18      time: meal.time
19    }
20  }
21
22  static get propTypes () {
23    return {
24      meal: PropTypes.any,
25      user: PropTypes.any,
26      toggle: PropTypes.func,
27      update: PropTypes.func
28    }
29  }
30
31  onChange (e) {
32    this.setState({ [e.target.name]: e.target.value })
33  }
34
35  create (e) {
36    e.preventDefault()
37
38    axios.post(API_URL + 'meals/', this.state, {
39      crossdomain: true,
40      headers: { Authorization: 'Token ' + this.props.user.token }
41    }).then((response) => {
42      this.props.toggle()
43      this.props.update()
44    })
45  }
46
47  edit (e) {
48    e.preventDefault()
49
50    if (this.state.date === '') delete this.state.date
51    if (this.state.time === '') delete this.state.time
52
53    axios.put(API_URL + 'meals/' + this.state.id + '/', this.state, {
54      crossdomain: true,
55      headers: { Authorization: 'Token ' + this.props.user.token }
56    }).then((response) => {
57      this.props.toggle()
58      this.props.update()
59    })
60  }
61
62  render () {
63    const boundChange = this.onChange.bind(this)
64
65    return (
66      <Form onSubmit={this.props.meal ? this.edit.bind(this) : this.create.bind(this)}>
67        <FormGroup>
68          <Label for='text'>Title:</Label>
69          <Input
70            type='text'
71            name='text'
72            onChange={boundChange}
73            value={this.state.text}
74          />
75        </FormGroup>
76        <FormGroup>
77          <Label for='text'>Calories:</Label>
78          <Input
79            type='text'
80            name='calories'
81            onChange={boundChange}
82            value={this.state.calories}
83          />
84        </FormGroup>
85        <FormGroup>
86          <Label for='text'>Date (empty for today):</Label>
87          <Input
88            type='date'
89            name='date'
90            onChange={boundChange}
91            value={this.state.date}
92          />
93        </FormGroup>
94        <FormGroup>
95          <Label for='time'>Time (empty for right now):</Label>
96          <Input
97            type='time'
98            name='time'
99            onChange={boundChange}
100            value={this.state.time}
101          />
102        </FormGroup>
103
104        <Button className='float-right' color='primary'>Save</Button>
105      </Form>
106    )
107  }
108}
109
110export default MealForm