3517
Mt
meal_tracker / files
meal_tracker / bmi_ui / src / components / UserForm.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 UserForm extends React.Component { 8 constructor (props) { 9 super(props) 10 11 this.state = { 12 id: this.props.user.id || '', 13 username: this.props.user.username || '', 14 preferences: this.props.user.preferences || { max_calories: 0 } 15 } 16 } 17 18 static get propTypes () { 19 return { 20 user: PropTypes.any, 21 toggle: PropTypes.func, 22 update: PropTypes.func 23 } 24 } 25 26 onChange (e) { 27 this.setState({ [e.target.name]: e.target.value }) 28 } 29 30 onCaloriesChange (e) { 31 this.setState({ preferences: { max_calories: e.target.value } }) 32 } 33 34 createUser (e) { 35 e.preventDefault() 36 37 axios.post(API_URL + 'users/', this.state, { crossdomain: true }).then(() => { 38 axios.post(API_URL + 'login/', this.state, { crossdomain: true }).then((res) => { 39 this.props.toggle() 40 this.props.update(res.data) 41 }) 42 }) 43 } 44 45 editUser (e) { 46 e.preventDefault() 47 48 axios.put(API_URL + 'users/' + this.state.id + '/', this.state, { 49 crossdomain: true, 50 headers: { Authorization: 'Token ' + this.props.user.token } 51 }).then((response) => { 52 const token = this.props.user.token 53 response.data.token = token 54 this.props.toggle() 55 this.props.update(response.data) 56 }) 57 } 58 59 render () { 60 const boundChange = this.onChange.bind(this) 61 const boundCaloriesChange = this.onCaloriesChange.bind(this) 62 63 return ( 64 <Form onSubmit={this.props.user ? this.editUser.bind(this) : this.createUser.bind(this)}> 65 <FormGroup> 66 <Label for='username'>Username:</Label> 67 <Input 68 type='text' 69 name='username' 70 onChange={boundChange} 71 value={this.state.username} 72 /> 73 </FormGroup> 74 <FormGroup> 75 <Label for='examplePassword'>Password:</Label> 76 <Input 77 type='password' 78 name='password' 79 onChange={boundChange} 80 value={this.state.password} 81 /> 82 </FormGroup> 83 <FormGroup> 84 <Label for='caloriesPerDay'>Maximum Calories per Day:</Label> 85 <Input 86 type='text' 87 name='caloriesPerDay' 88 onChange={boundCaloriesChange} 89 value={this.state.preferences.max_calories} 90 /> 91 </FormGroup> 92 93 <Button className='float-right' color='primary'>Save</Button> 94 </Form> 95 ) 96 } 97} 98 99export default UserForm