I have recently learned how to set up a simple api in my express server using a localhost mySQL database I have running on a MAMP server. After I set that up I learned how to have React.js fetch that data and display it. Now I want to do the reverse and post data from a form I created in React.js. I would like to continue using the fetch API to post that data. You can view my code below.
Below is my express server code for my api.
app.get('/api/listitems', (req, res) => {
connection.connect();
connection.query('SELECT * from list_items', (err,results,fields) => {
res.send(results)
})
connection.end();
});
I have already set up the form and created the submit and onchange functions for the form. When I submit data it is just put in an alert. I would like to have that data posted to the database instead. IBelow is the React App.js code.
import React, { Component } from 'react';
import './App.scss';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
formvalue: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleData = () => {
fetch('http://localhost:5000/api/listitems')
.then(response => response.json())
.then(data => this.setState({ items: data }));
}
handleChange(event) {
this.setState({formvalue: event.target.value});
}
handleSubmit(event) {
alert('A list was submitted: ' + this.state.formvalue);
event.preventDefault();
}
componentDidMount() {
this.handleData();
}
render() {
var formStyle = {
marginTop: '20px'
};
return (
<div className="App">
<h1>Submit an Item</h1>
<form onSubmit={this.handleSubmit} style={formStyle}>
<label>
List Item:
<input type="text" value={this.state.formvalue} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<h1>Grocery List</h1>
{this.state.items.map(
(item, i) =>
<p key={i}>{item.List_Group}: {item.Content}</p>
)}
<div>
</div>
</div>
);
}
}
export default App;