Search code examples
javascripthtmlnode.jsreactjsexpress

How to insert data from a React form to mysql?


I'm trying to develop my first react application. The backend works properly. Anyway I don't know how to insert the entered data in a react form into my database. I tried with axios, but I had many problems. Here is my code: Backend:

router.post('/insert',(req,res) =>{


    jsondata = req.body;
    description = jsondata['description'];
    distance = jsondata['distance'];
    hours = jsondata['hours'];
    minutes = jsondata['minutes'];
    seconds = jsondata['seconds'];


    conn.query('INSERT INTO run (description, distance, hours, minutes, seconds) VALUES (?,?,?,?,?)', [description,distance,hours,minutes,seconds], (err) =>{
        if(err)
        res.send(err)
        if(!err)
        res.send("Insert succeded.")
        
    })
})

Frontend:

import React, {useEffect, useState} from 'react';
import {Link} from 'react-router-dom';
function Insert(){

    return(

        <div>
            <form>
                <p>Insert the details of your run</p>
                <input type="text" id="description" placeholder="Insert a description of your run"></input>
                <input type="text" id="description" placeholder="Insert a description of your run"></input>
                <input type="number" id="description" placeholder="Insert the distance of your run"></input>
                <input type="number" id="description" placeholder="Insert the hours of your run"></input>
                <input type="number" id="description" placeholder="Insert the minutes of your run"></input>
                <input type="number" id="description" placeholder="Insert the seconds of your run"></input>
                <button id="btn">Submit</button>
            </form>
        </div>

    );


}

export default Insert;

Thank you so much for your help!


Solution

  • on inputs you need to put methods to handle their change, you can store values in useState, example:

    const [name, setName] = useState('');
    
    ...
    
    <input type="text" value={name} onChange={setName} />
    

    then, handle submit form by adding method call like this

    <form onSubmit={handleOnSubmit}>
    

    where you would gather your input data and sent it with axios, example:

     handleOnSubmit(e) {
            e.preventDefault()
    
            const data = {
              name: name
              // other fields...
    
            }
    
            axios.post('http://your-url.com', data)
                .then((res) => {
                    console.log(res.data)
                }).catch((error) => {
                    console.log(error)
                });
        }