Home > Enterprise >  How does one prevent a form from redirecting me? using ReactJS and ExpressJS
How does one prevent a form from redirecting me? using ReactJS and ExpressJS

Time:01-16

So I have a form and when I submit it, it redirects me to the route /repair, action of the form is /repair.

However what I'd like for it to do, is keep it all as a SPA, so when the form is submitted, the fields are removed and it just says "thank you" or something similar to that. is there a way to do that?

Frontend:

import React, { useState } from "react";
import { Grid, TextField, Button } from "@mui/material";
function Form(props) {
    let [data, setData] = useState({
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
        request: "",
    });
    const handleChange = (event) => {
        setData({ ...data, [event.target.name]: event.target.value });
        event.preventDefault();
    };
    return (
        <React.Fragment>
            <form action='/repair' method='POST'>
                <Grid container spacing={2}>
                    <Grid item xs={6}>
                        <TextField
                            sx='width: 80%'
                            id='form-first-name'
                            label='First Name'
                            variant='outlined'
                            name='firstName'
                        />
                    </Grid>
                    <Grid item xs={6}>
                        <TextField
                            sx='width: 80%'
                            id='form-last-name'
                            label='Last Name'
                            variant='outlined'
                            name='lastName'
                        />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            sx='width: 90%'
                            id='form-email'
                            label='Email'
                            variant='outlined'
                            name='email'
                        />{" "}
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            sx='width: 90%'
                            id='form-phone'
                            label='Phone'
                            variant='outlined'
                            name='phone'
                        />{" "}
                    </Grid>
                    <Grid item xs={12}>
                        <TextField
                            id='outlined-multiline-static'
                            multiline
                            rows={4}
                            placeholder='Let us know what your issue is:'
                            sx='width: 90%'
                            name='request'
                        />
                    </Grid>
                    <Grid item xs={12}>
                        <Button id='submit-repair-request' type='submit' variant='contained'>
                            Submit
                        </Button>
                    </Grid>
                </Grid>
            </form>
        </React.Fragment>
    );
}

export default Form;


Backend:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const path = require('path');
const crypto = require('crypto');
const mysql = require('mysql');

const db = mysql.createConnection({
    host:   'localhost',
    user:   'root',
    password:   '',
    database:   'dos-bros-it',
});

db.connect((err) => {
    if(err) {
        console.log(err.code);
        console.log(err.fatal);
    }else{
        console.log("Connection has been succesfully initiated!")
    }
})
const PORT = 7072;

app.use(express.static(path.join(__dirname, "client/build/")));
app.use(express.urlencoded({extended: true}));
app.use(express.json());

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, "client/public/", "index.html"));
});

app.post('/repair', (req, res, next) => {
    $query = "INSERT INTO tickets (firstName, lastName, email, phone, description) VALUES (?)";
        $data = [
        [req.body.firstName], 
        [req.body.lastName],
        [req.body.email], 
        [req.body.phone], 
        [req.body.request]
    ]
    db.query($query, 
    [$data], (err, rows, fields) => {
        if (!err) { 
            console.log('Repair was succesfully sent to the servers database! \n Records: '   rows);
        }else{
            console.log(err);
        }
    });
    console.log(req.body.firstName, req.body.lastName, req.body.email, req.body.phone, req.body.request);
    
    res.send("<h1>FORM SENT</h1>")
    next();
})
io.on("connection", (socket) => {
    console.log('Client has connected to the server!!!');
    socket.on('test', (msg)=>{
        console.log('recieved test message!!!', msg);
    })
})

http.listen(PORT, ()=>{
    console.log('Server Started using port:', PORT);
})

CodePudding user response:

Declare an handleSubmit method where you handle the form operations and call preventDefault() before your logic:

const handleSubmit = (e) => {
    e.preventDefault();

    fetch(`/repair`, {
        method: 'POST',
        ...
    })
}

Then, declare it in the form onSubmit method:

<form onSubmit={handleSubmit}>
  • Related