How to Post data to database using Fetch API in React.js

12,732

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));
  });
});
Share:
12,732

Related videos on Youtube

David Sanders
Author by

David Sanders

I am a web developer with design experience. Web development is not only my career but it is my hobby. I am trying to learn more front-end technologies so I can be a front-end web developer. This being learning ES6 javascript, fetch api, and React.js.

Updated on June 04, 2022

Comments

  • David Sanders
    David Sanders almost 2 years

    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;
    
    • Andrew Dibble
      Andrew Dibble over 5 years
      MDN has a good example of this in their docs actually.
    • Hemadri Dasari
      Hemadri Dasari over 5 years
      What’s the end point for post request?
    • David Sanders
      David Sanders over 5 years
      'http://localhost:5000/api/listitems'
  • David Sanders
    David Sanders over 5 years
    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.
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    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
    Hemadri Dasari over 5 years
    Please check my updated code. You can construct an object with all the values you want to send to the backend
  • David Sanders
    David Sanders over 5 years
    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".
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    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
  • David Sanders
    David Sanders over 5 years
    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.
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    Cheers😎 glad to help😊