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

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.

Related

I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql

i am using onKeyUp event for fire api without submitting the form and i fetched data in response successfully if Mobile number matched. But i don't understand how to display these data as a default value in columns. i also try to do this in useState default value but it doesn't work.
Please help me. Thank you!
Here is my code of frontend.
import React, { useEffect, useState } from 'react'
import { Alert } from 'react-bootstrap';
import { useForm } from 'react-hook-form';
const Billing = () => {
const [fill, setFill] = useState(false);
const [success, setSuccess] = useState(false);
const [customerDataFill, setCustomerDataFill] = useState()
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const [bill, setBill] = useState({
contactNo: "",
});
const OnKeyUpFunc = () =>{
const { contactNo } = bill;
axios.post("http://localhost:5000/getCustomerDetails", {
contactNo: contactNo,
})
.then((Rres) => {
setCustomerDataFill(Rres.data)
console.log(Rres.data, "<<<<-----This is customer details testing...");
});
}
//**I WANT TO DISPLAY THIS FETCHED CUSTOMER NAME IN CUSTOMER NAME COLUMN**
const GetCustNameFill = customerDataFill && customerDataFill.map((cData) => cData.Cust_Name)
const [customerName, setcustomerName] = useState("")
console.log(GetCustNameFill,"----<><><> GetCustNameFill fetch name checking")
const handleCustNameChange = (e) => {
setcustomerName(e.target.value);
// console.log(e, "this is e check...");
};
let name, value;
const handleInputs = (e) => {
console.log(e);
name = e.target.name;
value = e.target.value;
setBill({ ...bill, [name]: value });
setFill(false);
};
const onclick = async (e) => {
// e.preventDefault();
const { contactNo } =
bill;
try {
if (
customerName === "" ||
contactNo === ""
) {
setFill(true);
setSuccess(false);
} else {
setFill(false);
const config = {
header: {
"Content type": "appication/json",
},
};
const { data } = await axios.post(
"http://localhost:5000/billing_data",
{
cust_name : customerName,
contact_no : contactNo,
},
config
);
console.log(data);
localStorage.setItem("Billing_details", JSON.stringify(data));
setSuccess(true);
}
} catch (error) {
console.log(error);
}
};
return ( <>
<div className="modal fade" id="modalCenter" tabindex="-1" aria-hidden="true">
<div className="modal-dialog modal-dialog-centered modal-lg" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="modalCenterTitle">Bill information</h5>
<button
type="button"
className="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<form onSubmit={handleSubmit(onclick)} method="POST">
{fill && (
<div className="container mt-3">
<Alert variant="danger" style={{ fontSize: 15 }}>
<strong > Please Fill All the Required Field!</strong>
</Alert>
</div>
)}
{success && (
<div className="container mt-3">
<Alert variant="success" style={{ fontSize: 15 }}>
<strong style={{color:"green"}}>Bill Added Successssfully!</strong>
</Alert>
</div>
)}
{errors.contact && (
<div className="container mt-3">
<Alert variant="danger" style={{ fontSize: 15 }}>
<strong>{errors.contact.message}</strong>
</Alert>
</div>
)}
{errors.email && (
<div className="container mt-3">
<Alert variant="danger" style={{ fontSize: 15 }}>
<strong>{errors.email.message}</strong>
</Alert>
</div>
)}
<div className="modal-body">
<div className="row g-2">
<div className="col mb-2">
<label for="nameWithTitle" className="form-label">Contact No.</label>
<input
type="text"
id="nameWithTitle"
className="form-control"
placeholder="Enter Contact no."
value={bill.contactNo}
onChange={handleInputs}
name="contactNo"
onKeyUp={OnKeyUpFunc}
/>
</div>
<div className="col mb-2">
<label for="emailWithTitle" className="form-label">Customer name</label>
<input
type="text"
id="emailWithTitle"
className="form-control"
placeholder="Enter Customer Name"
value={customerName}
onChange={handleCustNameChange}
defaultValue={GetCustNameFill}
/>
</div>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-outline-secondary" data-bs-dismiss="modal">
Close
</button>
<button type="submit" className="btn btn-primary">submit</button>
</div>
</form>
</div>
</div>
</div>
</>
)
}
export default Billing
** Here is Backend Code**
var express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mysql = require("mysql");
const expressAsyncHandler = require("express-async-handler");
const generateToken = require("./jwtToken/generateToken");
const bcrypt = require("bcryptjs");
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "star_battery_db",
});
db.connect((err) => {
if (err) {
console.warn("Error in connection, Check XAMPP server");
} else {
console.warn("MySql db connected");
}
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(5000, () => console.log("Server is running on 5000"));
// Api for fetch Partcular customer data for billing.
app.post("/getCustomerDetails",expressAsyncHandler(async (req, res) => {
const contactNo = req.body.contactNo
const users = `SELECT * FROM cust_master WHERE Contact= ${db.escape(contactNo)}`;
db.query(users, (err, result) => {
if (err) {
res.status(404).send(err);
}
res.status(201).send(result);
});
})
); ```
I think that you don't need the customerDataFill state.
Using the customerName state should be enough.
Change your OnKeyUpFunc to set the customerName if a user with contactNo has been found and customerName was not set:
const [customerName, setcustomerName] = useState('');
const OnKeyUpFunc = () => {
const { contactNo } = bill;
axios
.post('http://localhost:5000/getCustomerDetails', {
contactNo: contactNo,
})
.then(({ data }) => {
// If at least a user with `contactNo` has been found, set `customerName`
if (data.length) {
setcustomerName(data[0].Cust_Name);
}
});
};
Finally, keep only the value in the emailWithTitle input:
<div className="col mb-2">
<label for="emailWithTitle" className="form-label">Customer name</label>
<input
type="text"
id="emailWithTitle"
className="form-control"
placeholder="Enter Customer Name"
value="{customerName}"
onChange="{handleCustNameChange}"
/>
</div>
This should work as an autocomplete when you change your nameWithTitle value and emailWithTitle has not been set.
You are directly sending the array inside the defaultValue of input. The defaultValue for input is expecting a text.
If you want to update the defaultValue through api below is the process.
Comment line const GetCustNameFill and console.log for GetCustNameFill.
Inside onKeyUp function use setCustomerDataFill(Rres.data[0]);
and change the input defaultValue variable from GetCustNameFill to customerDataFill.
defaultValue={customerDataFill.Cust_Name}

Wrong document gets updated when using updateDoc from Firebase/Firestore

I use prop drilling to pass down the id value of the document, but every time I click on a document to update it using updateDoc, the same document gets updated(always the latest one added), not the one I clicked on. I don't understand why the unique IDs don't get passed down correctly to the function, or whether that's the problem. I use deleteDoc this way and it's working perfectly. Any help will be appreciated.
This is where I get the id value from
const getPosts = useCallback(async (id) => {
const data = await getDocs(postCollectionRef);
setPosts(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
});
useEffect(() => {
getPosts();
}, [deletePost]);
return (
<div className={classes.home}>
<ul className={classes.list}>
{posts.map((post) => (
<BlogCard
key={post.id}
id={post.id}
title={post.title}
image={post.image}
post={post.post}
date={post.date}
showModal={showModal}
setShowModal={setShowModal}
deletePost={() => {
deletePost(post.id);
}}
showUpdateModal={showUpdateModal}
setShowUpdateModal={setShowUpdateModal}
/>
))}
</ul>
</div>
);
This is where I pass through the id value to the update modal component for each document:
function BlogCard(props) {
const [postIsOpen, setPostIsOpen] = useState(false);
const modalHandler = () => {
props.setShowModal((prevState) => {
return (prevState = !prevState);
});
};
const updateModalHandler = () => {
props.setShowUpdateModal((prevState) => {
return (prevState = !prevState);
});
};
const handleView = () => {
setPostIsOpen((prevState) => {
return (prevState = !prevState);
});
};
return (
<>
{props.showUpdateModal && (
<UpdateModal
showUpdateModal={props.showUpdateModal}
setShowUpdateModal={props.setShowUpdateModal}
id={props.id}
title={props.title}
image={props.image}
post={props.post}
/>
)}
{props.showModal && (
<DeleteModal
showModal={props.showModal}
setShowModal={props.setShowModal}
deletePost={props.deletePost}
/>
)}
<div className={classes.blogCard} id={props.id}>
<div className={classes.head}>
<p className={classes.title}> {props.title}</p>
<div className={classes.buttons}>
<button className={classes.editButton} onClick={updateModalHandler}>
Edit
</button>
<button className={classes.removeButton} onClick={modalHandler}>
Delete
</button>
</div>
</div>
<p className={classes.date}>{props.date}</p>
<img src={props.image} alt="image" />
{!postIsOpen ? (
<p className={classes.viewHandler} onClick={handleView}>
Show More
</p>
) : (
<p className={classes.viewHandler} onClick={handleView}>
Show Less
</p>
)}
{postIsOpen && <p className={classes.article}>{props.post}</p>}
</div>
</>
);
}
export default BlogCard;
Here I create the function to update and add the onclick listener
function UpdateModal(props) {
const [title, setTitle] = useState(props.title);
const [image, setImage] = useState(props.image);
const [post, setPost] = useState(props.post);
const updateModalHandler = (prevState) => {
props.setShowUpdateModal((prevState = !prevState));
};
const updatePost = async (id) => {
const postDocRef = doc(db, "posts", id);
props.setShowUpdateModal(false);
try {
await updateDoc(postDocRef, {
title: title,
image: image,
post: post,
});
} catch (err) {
alert(err);
}
};
return (
<div onClick={updateModalHandler} className={classes.backdrop}>
<form onClick={(e) => e.stopPropagation()} className={classes.form}>
<label htmlFor="title">Title</label>
<input
id="title"
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<label htmlFor="image">Image(URL)</label>
<input
id="image"
type="text"
value={image}
onChange={(e) => setImage(e.target.value)}
/>
<label htmlFor="post">Post</label>
<textarea
id="post"
cols="30"
rows="30"
value={post}
onChange={(e) => setPost(e.target.value)}
/>
<div className={classes.buttons}>
<button className={classes.cancel} onClick={updateModalHandler}>Cancel</button>
<button className={classes.update} onClick={() => updatePost(props.id)}>Update</button>
</div>
</form>
</div>
);
}
export default UpdateModal;
This is the way my data is structured
firebase

Re-rendering in my React sending email form

This is for api re-rendering issue, I want to know that how to call one api after selecting a dropdown option.
Here it re-render infinite time after selecting an-option in drop-down. I call an client Api from client collection and show in client drop down after I select drop down and going to the infinite loop.
import Select from "react-select";
import Axios from "axios";
import React, { useState, useEffect } from "react";
export default function Form() {
const [hday, setHday] = useState(null);
const [date, setDate] = useState(null);
const [hdata, setHdata] = useState([]);
const [hid, setHid] = useState(""); //changed use state value null to []
const [client, setClient] = useState([]);
const [clientvalue, setClientValue] = useState(null);
const [clientId, setClientId] = useState(""); //changed use state value null to []
const [cemail, setCemail] = useState([]);
const [clientname, setClientname] = useState(null);
const [clientEmail, setClientEmail] = useState([]);
const [message, setMessage] = useState("");
const [fromField, setFromField] = useState("");
const [loading, setLoading] = useState(false);
const handleRequest = async (e) => {
if (clientvalue && hday && fromField && cemail && clientEmail && message !== "") {
if (message !== "") {
e.preventDefault();
setLoading(true);
console.log({
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
});
const body = {
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
};
await Axios.post("http://localhost:3002/mail", body, {
headers: {
"Content-type": "application/json",
},
})
.then((res) => {
alert("Email Sent Successfully");
setLoading(false);
console.log(res);
window.location.reload();
})
.catch((err) => {
console.log(err);
setLoading(false);
});
} else {
alert("Compose Email");
}
} else {
alert("Please fill all required filled");
}
};
const fromFieldChange = (obj) => {
setFromField(obj.target.value);
};
const handleQuillChange = (e) => {
setMessage(e.target.value);
};
function handleHolidayChange(obj) {
console.log("This is object country", obj);
setHday(obj);
setHid(obj._id);
setDate(null);
}
//client call (repetadely call)
const onChangeClient = (obj) => {
console.log("client object", obj);
console.log("client object id", obj._id);
setClientValue(obj);
setClientId(obj._id);
setClientname(obj.client_name);
};
// console.log("This is client id and name", clientId + " " + clientname);
//(issues repetadely execute)
async function emailClick() {
const url = `http://localhost:3002/api/getClientEmail/${clientId}/${clientname}`;
Axios.get(url)
.then((response) => {
const temp = response.data.map((e) => e.email);
setCemail(temp);
console.log("Client Email", cemail);
})
.catch((error) => {
console.log(error);
});
}
emailClick();
const changeDate = async function dateClick() {
const url = `http://localhost:3002/api/holiday_date/${hid}`;
await Axios.get(url)
.then((response) => {
// console.log("This is holiday date",response.data[0]['date_of_holiday']);
setDate(response.data.date_of_holiday);
// console.log("holiday year",date);
})
.catch((error) => {
console.log(error);
});
};
changeDate();
useEffect(
() => {
async function getHoliday() {
const url = `http://localhost:3002/api/holidays`;
await Axios.get(url)
.then((response) => {
setHdata(response.data);
console.log("this is holiday", response.data);
})
.catch((err) => {
console.log(err);
});
}
getHoliday();
async function getClient() {
const url = `http://localhost:3002/api/client`;
await Axios.get(url)
.then((response) => {
setClient(response.data);
console.log("this is client", response.data);
})
.catch((err) => {
console.log(err);
});
}
getClient();
///api/emailtemplates
async function getClientEmail() {
const url = `http://localhost:3002/api/emailtemplates`;
await Axios.get(url)
.then((response) => {
setClientEmail(response.data.map((e) => e.subject));
})
.catch((err) => {
console.log(err);
});
}
getClientEmail();
},
[date],
[cemail],
);
return (
<form onSubmit={handleRequest} method="post">
<div className="form">
<div className="form__wrapper">
<div className="form__title">
{/* title */}
<h4>Holiday</h4>
</div>
<div className="form__container">
<div className="form__containerItems">
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Client</label>
</div>
<div className="form__containerItemField">
<Select
onChange={onChangeClient}
placeholder="Select Client"
value={clientvalue}
options={client}
getOptionLabel={(x) => x.client_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Holiday</label>
</div>
<div className="form__containerItemField">
<Select
onChange={handleHolidayChange}
placeholder="Select Holiday"
value={hday}
options={hdata}
getOptionLabel={(x) => x.holiday_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Date</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="date..." defaultValue={date} />
</div>
</div>
</div>
</div>
<div className="form__container">
<div className="form__containerItems">
{/* from */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>From</label>
</div>
<div className="form__containerItemField">
<input
type="email"
placeholder="Sender Email.."
// autoFocus="autoFocus"
value={fromField}
onChange={fromFieldChange}
/>
</div>
</div>
{/* to */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>To</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Client Emial.." defaultValue={cemail} />
</div>
</div>
{/* Subject */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Subject</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Write your Sub..." defaultValue={clientEmail} />
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Compose Mail</label>
<button
disabled={loading}
onClick={handleRequest}
type="submit"
className="btn btn-info"
>
Send
</button>
</div>
</div>
<div className="form__containerItem">
<div className="container__composeMail">
<textarea
value={message}
onChange={handleQuillChange}
className="quill"
placeholder="Enter Content from here..."
/>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
);
}

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.

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