React and node js form image submission - javascript

React js front end
const AddPost = ({setAlert}) => {
const [post, setPost] = useState({
name: '',
subject: '',
description: '',
categories: '',
errors: {}
});
const [file, setFile] = useState('');
const [category, setCategory] = useState([]);
useEffect(()=>{
axios.get('/api/categories')
.then((res)=>{
setCategory(res.data);
})
.catch(err => console.error(err))
},[]);
const {name, subject, description,categories} = post;
const onChangeHandler = e =>{
setFile(e.target.files[0]);
};
const onChange = e =>{
setPost({...post, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
const formData = new FormData();
formData.append('myImage',file);
const config = {
headers:{'Content-Type': 'multipart/form-data'}
};
const data = {
name: name,
subject: subject,
description: description,
categories: categories,
...formData
};
axios.post('/api/articles/add',data,config)
.then( res => {
console.log('success test', res.data);
setAlert('Article Added','success');
})
.catch((err) => {
console.log('error failed',err);
});
setPost({
name: '',
subject: '',
description: '',
categories: '',
});
setFile({file:''})
};
return (
<Fragment>
<div className="container">
<div className="row justify-content-center">
<div className="col-6">
<h3>Add Posts</h3>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input
type="text"
name='name'
value={name}
className="form-control"
placeholder="Authors name"
onChange={e => onChange(e)}
/>
</div>
<div className="form-group">
<input
type="text"
name='subject'
value={subject}
className="form-control"
placeholder="subject"
onChange={e => onChange(e)}
/>
</div>
<div className="form-group">
<select name='categories'
value={categories}
onChange={e => onChange(e)}
className="form-control">
<option selected>Choose category</option>
{
category.map((item,index)=>(
<option key={index}
>{item.name}
</option>
))
}
</select>
</div>
<div className="form-group">
<textarea
rows="6"
className="form-control"
name='description'
value={description}
placeholder="content"
onChange={e => onChange(e)}> </textarea>
</div>
<input type="file" name='myImage' onChange={e => onChangeHandler(e)} />
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</Fragment>
);
};
This is code for node backend
router.post('/add',(req,res) => {
upload(req,res,(err) => {
if(err){
res.send(err);
}else{
console.log(req.file);
res.send('test');
}
});
var name = req.body.name;
var subject = req.body.subject;
var description = req.body.description;
var categories = req.body.categories;
if(req.file){
var myImage = req.file.filename
}else{
myImage = 'noImage2.jpg'
}
newArticle = new Article({
name: name,
subject: subject,
description: description,
categories: categories,
image: myImage
});
newArticle.save();
try{ res.send('success')}
catch{res.status(400).json('error')}
});`
I have a react blog that contains authors name, title, body and image, I'm using multer in my node server to handle image upload but i don't know how to send both the image and other form data together. I can send them separately. But i need to send them together I've tried formData. Please any help will be appreciated.

Related

How to display images

When I store my image in mysql it get stored as a blob and when i try to display it the image does not show up. I have tried to find how to display it but had no luck. Can anyone help me. The first piece of code is the form and the next piece which starts with const express is where the data gets sent to the mysql server.
import React, {Component} from "react";
import axios from "axios";
import {Redirect} from 'react-router-dom'
export default class Sell extends Component{
constructor(){
super()
this.state={
img:"",
dropdownval:'',
h:1
}
}
handleSubmit = e =>{
e.preventDefault()
const data={
tiTle:this.product,
descripTion:this.description,
condiTion:this.state.dropdownval,
quanTity:this.quantity,
prIce:this.price,
picTure:this.state.img
}
axios.post('http://localhost:3001/sell/listing',data).then(
res => {
console.log(res)
}
).catch(
err=>{
console.log(err)
}
)
this.setState({
h:0
})
}
onImageChange =(e)=>{
const [file] = e.target.files
this.setState({
img:URL.createObjectURL(file)
})
}
onDropdownChange =(e)=>{
this.setState({ dropdownval:e.target.value });
}
render(){
if(this.state.h===0){
return <Redirect to={'/'}/>
}
return(
<form className="sellForm" onSubmit={this.handleSubmit}>
<h3>Sell</h3>
<div className="form-group">
<label>Product Title</label>
<input type="text" className="form-control" required
onChange={e => this.product= e.target.value}/>
</div><br/>
<div className="form-group">
<label>Description</label><br/>
<textarea className="description" type="text" required
onChange={e => this.description= e.target.value}/>
</div><br/>
<label>Condition:</label><br/>
<select onChange={this.onDropdownChange}>
<option value="new">New</option>
<option value="slightly-used">Slightly Used</option>
<option value="used">Used</option>
</select>
<div className="form-group">
<br/><label>Quantity:</label><br/>
<input className="form-control" type="number" min="0" required
onChange={e => this.price= e.target.value}/>
</div><br/>
<div className="form-group">
<label>Price:</label><br/>
<span>$</span>
<input className="form-control" type="number" min="0" required
onChange={e => this.quantity= e.target.value}/>
</div><br/>
<div className="form-group">
<br/><label className="img-label">Insert Image</label>
<input type="file" onChange={this.onImageChange}/>
<img className="sellImg"src={this.state.img}/>
</div><br/>
<button className="btn btn-primary btn-block">
Upload Listing
</button>
</form>
)
}
}
const express = require("express")
const bodyParser=require("body-parser")
const app = express();
const cors=require("cors")
const mysql = require("mysql");
app.post("/sell/listing",(req,res)=>{
const title = req.body.tiTle
const description = req.body.descripTion
const condition = req.body.condiTion
const quantity = req.body.quanTity
const price = req.body.prIce
const pic = req.body.picTure
sqlInsert="INSERT INTO listings (name,price,description,condi,quantity,picture) VALUES(?,?,?,?,?,?)"
db.query(sqlInsert,[title,price,description,condition,quantity,pic], (err,result)=>{
console.log(err)
})
})
app.get("/api/get", (req, res) => {
const sqlSelect = "SELECT * FROM listings";
db.query(sqlSelect, (err, result) => {
res.send(result)
})
})
app.listen(3001, () =>{
console.log("running on port 3001");
});
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "cruddatabase",
})

Cant Update The state after getting data from the input React js

as u see in the code I'm tryin to get the "ProductionName" from the server "getManuficturedProduction" and display that into the input and after that I want to get the input value and post it to the server but idk why my set state doesn't update and still show me the default value.when i log my set state "assignProductToProductionline" i can see that my "ProductionName" did not updated
const [assignProductToProductionline, SetAssignProductToProductionline] =
useState({
Id: "",
ProductionCode: "",
ProductionName: "",
});
useEffect(() => {
loadProductionLine();
}, []);
const [productionLineName, SetProductionLineName] = useState([]);
const loadProductionLine = async () => {
const result = await axios.get(
"url"
);
SetProductionLineName(result.data);
};
const getManuficturedProduction = async () => {
var res = await axios.get(
`url`
);
var GetInfo = res.data.Result;
SetAssignProductToProductionline({
ProductionName: `${GetInfo.Name}`,
});
};
const { Id, ProductionCode, ProductionName } = assignProductToProductionline;
const onInputChange = (e) => {
SetAssignProductToProductionline({
...assignProductToProductionline,
[e.target.name]: e.target.value,
});
};
const onSubmit = async (e) => {
await axios
.post(
"url",
assignProductToProductionline
)
.catch(function (error) {
if (error.response) {
return toast.error(error.response.data);
}
});
navigate("/productionLineProduct");
};
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5 mt-5">
<form onSubmit={(e) => onSubmit(e)}>
<div className="form-group">
<select
className="form-control form-control-md mb-2 "
type="text"
name="Id"
value={Id}
onChange={(e) => onInputChange(e)}
autoComplete="off"
>
{productionLineName.map((cs) => (
<option key={cs.Id} value={cs.Id}>
{cs.ProductionLineName}
</option>
))}
</select>
</div>
<div className="form-group mb-2">
<input
id="customeProductionCode"
type="number"
className="form-control form-control-md"
name="ProductionCode"
value={ProductionCode}
onChange={(e) => onInputChange(e)}
autoComplete="off"
onInput={(e) => (e.target.value = e.target.value.slice(0, 9))}
/>
<a
className="btn btn-outline-success px-4"
onClick={(e) => getManuficturedProduction(e)}
>
check it
</a>
<div className="mt-2">
<input
className="text-success w-50"
name="ProductionName"
defaultValue=""
value={ProductionName}
placeholder={ProductionName}
onChange={(e) => onInputChange(e)}
/>
</div>
</div>
<button className="btn btn-primary w-25 ">save</button>
</form>
</div>
</div>
);
};
export default AssignProductToProductionLine;
{
you have to use assignProductToProductionline.ProductionName.
This line
const { Id, ProductionCode, ProductionName } = assignProductToProductionline;
creates a constant that is initialized with the first value and never changed.

API resolved without sending a response for /api/xyz. How do I resolve this error in NextJS

I am currently working on an e-commerce site in React/NextJS, and am having trouble working out why my api endpoints are not sending a response. The same problem exists for both the addProduct and updateProduct endpoints. The products are added/updated just fine but I have this error and I am not getting any other useful error messages, likely because I am not using try/catch statements properly, but I am unsure!
addproduct.js 'api/addproduct'
import {connectToDatabase} from '../../lib/mongodb'
async function addProduct(item){
const { db } = await connectToDatabase();
const resp = await db
.collection("stock")
.insertOne(item)
return resp
}
const post = async (req, res) => {
try {
var colourList=[]
var sizeList=[]
Object.keys(req.body).forEach( key => {
if (key.substring(0,7) == "colour-"){
colourList.push(req.body[key])
}
if (key.substring(0,9) == "checkbox-"){
sizeList.push(key.substring(9))
}
})
// Extract Form Data
var newItem = {
id : req.body["id"],
name : req.body["name"],
description : req.body["description"],
gender : req.body["gender"],
price : req.body["price"],
isOnSale : req.body["isOnSale"],
discount : req.body["discount"],
colours : colourList,
sizes : sizeList,
}
// debug
console.log(req.body)
// add the stock to the db
const resp = await addProduct(newItem)
res.status(201).send({ message: "Item Added", response: resp })
return
}
catch (err) {
res.status(err).json({});
}
};
export default (req, res) => {
req.method === "POST"
? post(req, res)
: req.method === "PUT"
? console.log("PUT")
: req.method === "DELETE"
? console.log("DELETE")
: req.method === "GET"
? console.log("GET")
: res.status(404).send("");
};
updateproduct.js 'api/updateproduct'
import {connectToDatabase} from '../../lib/mongodb'
async function updateProduct(updatedItem){
var query = { id: updatedItem.id };
var newValues =
{ $set: {
id: updatedItem.id,
name: updatedItem.name,
description: updatedItem.description,
gender: updatedItem.gender,
price: updatedItem.price,
isOnSale: updatedItem.isOnSale,
discount: updatedItem.discount,
colours: updatedItem.colours,
sizes: updatedItem.sizes
}
};
// debug
console.log("newValues:")
console.log(newValues)
const { db } = await connectToDatabase();
const resp = await db
.collection("stock")
.updateOne(query, newValues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
});
return resp
}
const post = async (req, res) => {
var colourList=[]
var sizeList=[]
Object.keys(req.body).forEach( key => {
if (key.substring(0,7) == "colour-"){
colourList.push(req.body[key])
}
if (key.substring(0,9) == "checkbox-"){
sizeList.push(key.substring(9))
}
})
// Extract Form Data
var updatedItem = {
id : req.body['id'],
name : req.body['name'],
description : req.body['description'],
gender : req.body['gender'],
price : req.body['price'],
isOnSale : req.body['isOnSale'],
discount : req.body['discount'],
colours : colourList,
sizes : sizeList,
}
// debug
console.log("Body:")
console.log(req.body)
// update the stock in db
const resp = await updateProduct(updatedItem)
res.status(201).send({ message: 'Item Updated' })
return
};
export default (req, res) => {
req.method === "POST"
? post(req, res)
: req.method === "PUT"
? console.log("PUT")
: req.method === "DELETE"
? console.log("DELETE")
: req.method === "GET"
? console.log("GET")
: res.status(404).send("");
};
AddProductForm.js
import React, {useState} from 'react';
import { useRouter } from 'next/router'
import {Form} from 'react-bootstrap'
export default function AddProductForm({ }) {
const router = useRouter()
// userInput is for adding colours.
const [userInput, setUserInput ] = useState('');
// Form State Variables
const [id, setId] = useState('')
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [gender, setGender] = useState('')
const [price, setPrice] = useState('')
const [isOnSale, setIsOnSale] = useState('')
const [discount, setDiscount] = useState('')
const [colours, setColours ] = useState([]);
var sizesList = {
"checkbox-xs":false,
"checkbox-s":false,
"checkbox-m":false,
"checkbox-l":false,
"checkbox-xl":false,
"checkbox-xxl":false}
const [sizes, setSizes] = useState(sizesList)
const handleAddProduct = async event => {
event.preventDefault();
var body = {id: id,
name: name,
description: description,
gender: gender,
price: price,
isOnSale: isOnSale,
discount: discount}
colours.forEach( (colour, index) => {
body[`colour-${index}`]= colour.colour})
Object.keys(sizes).forEach( (key, index) => {
if(sizes[key] == true) {
body[key] = true
}
})
const options = {
body: JSON.stringify(body),
method: "POST",
headers: {
'Content-Type': 'application/json'
},
}
const response = await fetch(
"/api/addproduct", options
)
var message = await response.json();
alert(message['message'])
router.push("/admin/inventory")
//document.getElementById("add-item-form").reset();
// .then(response => {
// alert(response['message'])
// router.push("/admin/inventory")
// })
// .catch(error => {
// console.log(error)
// })
}
const handleChangeColour = (e) => {
setUserInput(e.currentTarget.value)
}
const handleRemoveColour = (e) => {
e.preventDefault();
const colourId = e.target.getAttribute("name")
setColours(colours.filter(colour => colour.id != colourId));
}
const addColour = (userInput) => {
let copy = [...colours];
setColours(copy);
copy.push({id: colours.length + 1, colour: userInput});
}
const handleAddColour = (e) => {
e.preventDefault();
addColour(userInput);
setUserInput("");
}
const handleChangeSizes = (e) => {
sizesList = sizes
sizesList[e.target.name] = e.target.checked
setSizes(sizesList)
}
return (
<Form id="add-item-form" onSubmit={handleAddProduct}>
<div className="row">
<div className ="col-lg-6">
<Form.Group className="mb-3" controlId="formProductId">
<Form.Control type="text" name="formProductId" placeholder="Enter Product Id" onChange={e => setId(e.target.value)} required/>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductName">
<Form.Control name="formProductName" type="text" placeholder="Enter Product Name" onChange={e => setName(e.target.value)}required/>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductGender">
<Form.Select name="formProductGender" aria-label="Gender Select" onChange={e => setGender(e.target.value)} required>
<option>Is this male, female, or both</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Unisex">Unisex</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductPrice" >
<Form.Control name="formProductPrice" type="number" placeholder="Enter Product Price" onChange={e => setPrice(e.target.value)} required/>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductDiscount">
<Form.Control name="formProductDiscount" type="number" placeholder="Enter Current Discount (in %)" onChange={e => setDiscount(e.target.value)} required/>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductIsOnSale">
<Form.Select name="formProductIsOnSale" aria-label="Sale Select" onChange={e => setIsOnSale(e.target.value)} required>
<option>Is this product on sale?</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Form.Select>
</Form.Group>
</div>
<div className ="col-lg-6">
<Form.Group className="mb-3 " controlId="formProductDescription">
<Form.Control name="formProductDescription" type="text" placeholder="Enter Product Description" onChange={e => setDescription(e.target.value)} required/>
</Form.Group>
<Form.Group className="mb-3 " controlId="formProductSizes">
<Form.Label>Available Sizes</Form.Label>
<div className="row">
<div className="col-sm-2"></div>
<div className="col-sm-8">
<div className="row">
{['xs', 's', 'm', 'l', 'xl', 'xxl'].map(function(size, index){
return (
<div className="col" key={index}>
<Form.Check
type='checkbox'
id={`checkbox-${size}`}
name={`checkbox-${size}`}
label={`${size}`}
onChange={handleChangeSizes}
/>
</div>
)})}
</div>
</div>
<div className="col-sm-2"></div>
</div>
</Form.Group>
<Form.Group className="mb-3" controlId="formProductColours">
<div className="row">
<div className="col">
<Form.Label className="ml-5">Available Colours</Form.Label>
</div>
<div className="col">
<input value={userInput} type="text" onChange={handleChangeColour} placeholder="Enter Colour..."/>
</div>
<div className="col pb-1">
<div className="btn btn-outline-success btn-sm mb-1" onClick={handleAddColour}>+</div>
</div>
</div>
{colours.map(colour => {
return (
<>
<div className="row" key={colour.id}>
<div className="col">
<div > {colour.colour} </div>
</div>
<div className="col">
<div className="col pb-1">
<div name={colour.id} class="btn btn-outline-success btn-sm mb-1" onClick={handleRemoveColour}>-</div>
</div>
</div>
</div>
<input type="hidden" name={`colour-{colour.colour}`}></input>
</>
)
})}
</Form.Group>
</div>
</div>
<button type="submit" className="btn btn-outline-success">
Add Product
</button>
</Form>
)
}
I'd like help working out why the api isn't sending a response or error, and also how do I effectively deal with errors using try/catch. Am I right just to wrap all the code inside the function in a try/catch block?
any assistance always appreciated.
UPDATED I have added the AddProductForm.js to show how I am calling the api route.

Check to compare password field with confirm password reactjs/spring boot

Im making a sign up form with reactjs and spring boot but having some issues with trying to confirm a password by comparing it to the original entered password.
At the moment, I have this structure in my Java entity class (each are form fields, but i do not have the confirmPassword field here)
Java Entity class for form fields
I am using these bean validations to display in the react frontend, but the part I'm struggling with is to compare the password field with the confirm password field.
At the moment I have checks to see if the password matches the original password, but when I submit the form and enter incorrect data in the confirm password field, it still posts the data.
Form passwords
Since I don't have validation in my java class for the confirm password field, I am struggling to prevent the form data from posting if the passwords do not match.
This is my react form at the moment
import React, { useState, useEffect } from 'react'
import 'react-datepicker/dist/react-datepicker.css'
const RegistrationForm = () => {
// customer obj
const [customer, setCustomerData] = useState({
firstName: "",
lastName: "",
emailAddress: "",
mobileNumber: "",
dateOfBirth: new Date(),
password: "",
confirmPassword: ""
});
// error fields to display on form
const [firstNameError, setFirstNameError] = useState("");
const [lastNameError, setLastNameError] = useState("");
const [emailAddressError, setEmailAddressError] = useState("");
const [mobileNumberError, setMobileNumberError] = useState("");
const [dateOfBirthError, setDateOfBirthError] = useState("");
const [passwordError, setPasswordError] = useState("");
const [passwordShown, setPasswordShown] = useState("");
const togglePassword = () => {
setPasswordShown(prevPass => !prevPass);
}
// Handle all other controlled fields
const handleChange = (event) => {
const { name, value } = event.target;
setCustomerData(prev => ({
...prev,
[name]: value
}));
}
const calculateAge = (dob) => {
let birthDate = new Date(dob);
const difference = Date.now() - birthDate.getTime();
const age = new Date(difference);
const calculation = Math.abs(age.getUTCFullYear() - 1970);
return calculation;
}
// Handle date change
const handleDateChange = (event) => {
setCustomerData(prev => ({
...prev,
dateOfBirth: event.target.value
}))
};
const handleEmailChange = (event) => {
setCustomerData(prev => ({
...prev,
emailAddress: event.target.value
}))
}
// Handle Mobile number change
const handleMobileNumberChange = (event) => {
let val = event.target.value;
val = val.replace(/[^0-9]/gm, '');
let num = `${val.substring(0, 3)} ${val.substring(3, 6)} ${val.substring(6, val.length)}`;
num = num.trim();
setCustomerData(prev => ({
...prev,
mobileNumber: num
}))
};
const handlePasswordChange = (event) => {
const { name, value } = event.target;
setCustomerData(prev => ({
...prev,
[name]: value
}));
}
// on each render compare password with confirm password field
useEffect(() => {
checkPassword(customer);
},[customer])
// check if the password matches confirm password,
const checkPassword = (customer) => {
if(customer.password === customer.confirmPassword) {
setPasswordError("Passwords match");
} else if(customer.password !== customer.confirmPassword) {
setPasswordError("Passwords don't match")
} else {
setPasswordError("")
}
}
// submit form data
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log("Age: " + calculateAge(customer.dateOfBirth));
fetch("http://localhost:8080/api/v2/register", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
firstName: formData.get('firstName'),
lastName: formData.get('lastName'),
emailAddress: formData.get('emailAddress'),
mobileNumber: formData.get('mobileNumber'),
dateOfBirth: formData.get('dateOfBirth'),
password: formData.get('password')
}),
})
.then((response) => response.json())
.then((data) => {
if(data.fieldErrors) {
data.fieldErrors.forEach(fieldError => {
if(fieldError.field === 'firstName') setFirstNameError(fieldError.message);
if(fieldError.field === 'lastName') setLastNameError(fieldError.message);
if(fieldError.field === 'emailAddress') setEmailAddressError(fieldError.message);
if(fieldError.field === 'mobileNumber') setMobileNumberError("Mobile Number is invalid.");
if(fieldError.field === 'dateOfBirth') setDateOfBirthError(fieldError.message);
if(fieldError.field === 'password') setPasswordError(fieldError.message);
});
} else {
setCustomerData({
firstName: '',
lastName: '',
emailAddress: '',
mobileNumber: '',
dateOfBirth: new Date(),
password: '',
confirmPassword: ''
})
alert("Data posted successfully");
}
})
.catch((err) => console.log("ERROR: " + err));
}
return (
<div className="register-form-background">
<form className="register-form-bg" id="register-form" method="POST" onSubmit={handleSubmit}>
<h2 className="register-form-heading">Register</h2>
<div className="register-form-fields">
<div className="row">
{/*First Name*/}
<div className="col-sm">
<div className="form-group">
<label htmlFor="firstName" className="register-form-labels">First name</label>
{firstNameError ? <span className="field-validation-styling">{firstNameError}</span> : ''}
<input type="text"
onFocus={() => setFirstNameError('')}
className="shadow-none form-control register-form-input-field"
name="firstName"
placeholder="Enter First Name"
value={customer.firstName}
onChange={handleChange}
/>
</div>
</div>
<div className="col-sm">
{/*Last Name*/}
<div className="form-group">
<label htmlFor="lastName" className="register-form-labels">Last name</label>
{lastNameError ? <span className="field-validation-styling">{lastNameError}</span> : ''}
<input type="text"
onFocus={(e) => setLastNameError('')}
className="shadow-none form-control register-form-input-field"
name="lastName"
placeholder="Enter Last Name"
value={customer.lastName}
onChange={handleChange}
/>
</div>
</div>
</div>
{/*Email Address*/}
<div className="form-group">
<label htmlFor="emailAddress" className="register-form-labels">Email Address</label>
{emailAddressError ? <span className="field-validation-styling">{emailAddressError}</span> : ''}
<input type="email"
//required
onFocus={(e) => setEmailAddressError('')}
className="shadow-none form-control register-form-input-field"
name="emailAddress"
placeholder="Enter Email Address"
value={customer.emailAddress}
onChange={handleEmailChange}
/>
</div>
{/*Contact Number*/}
<div className="form-group">
<label htmlFor="mobileNumber" className="register-form-labels">Mobile Number</label>
{mobileNumberError ? <span className="field-validation-styling">{mobileNumberError}</span> : ''}
<input type="tel"
onFocus={(e) => setMobileNumberError('')}
className="shadow-none form-control register-form-input-field"
name="mobileNumber"
id="mobileNumber"
placeholder="Enter Mobile Number"
maxLength="12"
value={customer.mobileNumber}
onChange={handleMobileNumberChange}
/>
</div>
{/*Date Of Birth*/}
<div className="form-group">
<label htmlFor="dateOfBirth" className="register-form-labels">Date Of Birth</label>
{dateOfBirthError ? <span className="field-validation-styling">{dateOfBirthError}</span> : ''}
<input type="date"
onFocus={(e) => setDateOfBirthError('')}
className="shadow-none form-control register-form-input-field"
name="dateOfBirth"
max="2010-01-01"
selected={customer.dateOfBirth}
onChange={handleDateChange}
/>
</div>
{/*Password*/}
<div className="form-group">
<label htmlFor="password" className="register-form-labels">Password</label>
{passwordError ? <span className="field-validation-styling">{passwordError}</span> : ''}
<input type={passwordShown ? "text" : "password"}
onFocus={(e) => setPasswordError('')}
className="shadow-none form-control register-form-input-field"
name="password"
placeholder="Enter Password"
value={customer.password}
onChange={handlePasswordChange}
/>
</div>
{/*Confirm Password*/}
<div className="form-group">
<label htmlFor="confirmPassword" className="register-form-labels">Confirm Password</label>
<input type={passwordShown ? "text" : "password"}
minLength="8"
className="shadow-none form-control register-form-input-field"
name="confirmPassword"
placeholder="Confirm Password"
value={customer.confirmPassword}
onChange={handlePasswordChange} />
</div>
{/*Checkbox to show password*/}
<div className="form-check register-show-password-group">
<input type="checkbox" className="shadow-none form-check-input register-form-check-field" onChange={togglePassword} />
<label className="form-check-label register-show-password-lbl">Show password</label>
<label className="form-check-label register-forgot-password-lbl">Forgot password?</label>
</div>
<button type="submit" className="shadow-none btn register-btn">Create Account</button>
<label className="form-labels" className="form-check-label sign-in-lbl">Already have an account? <span style={{ color: "#A7E25E", textDecoration: "none" }}>Sign in</span></label>
</div>
</form>
</div>
)
}
export default RegistrationForm;
This should work
const handleSubmit = (e) => {
const formData = new FormData(e.target);
if (formData.get('password') == '' || formData.get('password') != formData.get('confirmPassword') ) {
e.preventDefault();
return;
}
Suppose you just started with React. tbh the code is far from a production code. I would suggest to check https://react-hook-form.com/ and adopt it for your purpose.
Also, use some light momentjs-like lib like https://date-fns.org/v2.24.0/docs/sub
https://jsfiddle.net/pLcewunx/

Set state using onChange using hook

I want to get the value when I change it with onChange and created a name and contact number by using the value and setContacts, this app does not cause error but it does not work, Where is the problem? Thanks.
Each new contact in an object has an id, a name and a phone number
const AddUSer = () => {
const {contacts, setcontacts}=useState([]);
const { userName, setUSerName } = useState("");
const { userPhone, setUserPhone } = useState("");
const setName = (e) => {
const value = e.target.value;
return setUSerName(value);
};
const setPhone = (e) => {
const value = e.target.value;
return setUserPhone(value);
};
const handleNewcontact = () => {
const allcontacts = [...contacts];
const newContact = {
id: Math.floor(Math.random() * 1000),
fullName: userName,
phone: userPhone,
};
allcontacts.push(newContact);
setcontacts(allcontacts);
setUSerName("");
setUserPhone("");
}
};
return (
<div className="container">
<form>
<label>Name</label>
<input className="form-control" onChange={(e) => setName} />
<label>Phone</label>
<input className="form-control" onChange={(e) => setPhone} />
<button
onClick={handleNewcontact}
className="btn btn-primary mt-3 mb-4"
>
Save
</button>
</form>
</div>
);
};
export default AddUSer;
You are not passing the event to the function. You can either do
onChange={(e) => setName(e)}
onChange={(e) => setPhone(e)}
but better:
onChange={setName}
onChange={setPhone}
try this. the values are consoled when the user clicks the submit button.
const AddUSer = () => {
const [contact, setContact] = useState({id: '', userName:'', userPhone:''});
function handleNewContact(event) {
setContact({
...contact, id: Math.floor(Math.random() * 1000),
[event.target.name]: event.target.value
});
}
function handleSubmit(event) {
event.preventDefault();
console.log(contact);
}
return (
<div className="container">
<form>
<label>Name</label>
<input className="form-control" name='userName'
onChange={handleNewContact} />
<label>Phone</label>
<input className="form-control" name='userPhone'
onChange={handleNewContact} />
<button
onClick={handleSubmit}
className="btn btn-primary mt-3 mb-4"
>
Save
</button>
</form>
</div>
);
};
export default AddUSer;

Categories

Resources