Reputation: 13
I created a register page for my web Application using React. Here is my Code for Register Component -
import React, { useState } from 'react';
import { Avatar, Button, Paper, Grid, Typography, Container } from '@material-ui/core';
import axios from "axios";
import useStyles from './styles';
import Input from './Input';
const initialState = { name: '', email: '', password: '', mobile: '', confirmPassword: '' };
const Register = () => {
const [form, setForm] = useState(initialState);
const classes = useStyles();
const handleSubmit = async () => {
const { data } = await axios.post('http://localhost:4000/users/register', initialState);
console.log(data);
};
const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });
return (
<div>
<Container component="main" maxWidth="xs">
<Paper className={classes.paper} elevation={3}>
<Typography component="h1" variant="h5">Sign up</Typography>
<form className={classes.form} onSubmit={handleSubmit}>
<Grid container spacing={2}>
<Input name="name" label="Full Name" handleChange={handleChange} autoFocus/>
<Input name="mobile" label="Mobile Number" handleChange={handleChange}/>
<Input name="email" label="Email Address" handleChange={handleChange} type="email"/>
<Input name="password" label="Password" handleChange={handleChange} type='password'/>
<Input name="confirmPassword" label="Confirm Password" handleChange={handleChange} type="password"/>
</Grid>
<Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
Sign Up
</Button>
</form>
</Paper>
</Container>
</div>
);
};
export default Register;
When a form is submitted, no request is made on the server side. Instead, it redirects to the same page again with query parameters equal to the input bodies of the form. What am I doing wrong here?
Upvotes: 1
Views: 63
Reputation: 39
Use event.preventDefault() in handelSubmit as it will stop the default action of the browser which is reloading on submititing a a form.
const handleSubmit = async (event) => {
event.preventDefault();
// other line of code
};
Upvotes: 0
Reputation: 2857
You aren't preventing the default action of the form. Since you are using a standard html form, submitting it will just default to a get request which would include the values in the url like you have said.
Preventing the default will allow you to then do a non default action like the axios call you want.
const handleSubmit = async (e) => {
e.preventDefault()
const { data } = await axios.post('http://localhost:4000/users/register', initialState);
console.log(data);
};
Upvotes: 1