2

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;
David Sanders
  • 131
  • 1
  • 3
  • 16

1 Answers1

4

You can do something like below

handleSubmit (event) {
  //alert('A list was submitted: ' + this.state.formvalue);
  event.preventDefault();
  fetch('your post url here', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      id: this.state.id,
      item: this.state.item,
      itemType: this.state.itemType
    })
  })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err);
}

My working post endpoint is below.

app.post('/api/listitems', (req, res) => {
  var postData  = req.body;
  connection.query('INSERT INTO list_items SET ?', postData, (error, results, fields) => {
    if (error) throw error;
    res.end(JSON.stringify(results));
  });
});
Damon
  • 4,216
  • 2
  • 17
  • 27
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
  • Just a question the about this. My mySQL table is set up like this. Row => ID, Item, ItemType, Date. If my form only has one field, lets say to accept a new ItemType value. How does handleSubmit know where to place this data. Again I am very new to fetching data across a network and I am just trying to understand this better. – David Sanders Jan 22 '19 at 04:20
  • I though the state formValue is an object. You need to manually construct an object with relevant data inside handleSubmit and pass the data object to JSON.stringify(data) in the body of fetch post request – Hemadri Dasari Jan 22 '19 at 04:31
  • Please check my updated code. You can construct an object with all the values you want to send to the backend – Hemadri Dasari Jan 23 '19 at 03:17
  • I constructed the object and put some filler text in the states. When i run the handleSubmit function it throws these errors in the console. Not sure what this means. `POST http://localhost:5000/api/listitems 404 (Not Found) App.js:49 SyntaxError: Unexpected token < in JSON at position 0 Fetch failed loading: POST "http://localhost:5000/api/listitems".` – David Sanders Jan 23 '19 at 05:49
  • Looks like the url you specified isn’t found in the backend so make sure you give right end point and regarding unexpected token I have updated my code in answer take that and try – Hemadri Dasari Jan 23 '19 at 09:41
  • 1
    Yes you were write. My post endpoint was not set up correct. Now it it is set up and everything is posting to the database fine. – David Sanders Jan 24 '19 at 04:29
  • Cheers glad to help – Hemadri Dasari Jan 24 '19 at 05:34