ctx.t0.response is undefined nextjs - javascript

I am new in reactjs and working on nextjs framework,i am trying to integrate "newsletter" section,for this
i created "api" so whenever i pass email in url, email will be save in my db via api, so now i am trying to use this
api in "newsletter" section but i am getting following error
"TypeError: _ctx.t0.response is undefined"
Here is my api url
https://myurl.com?email=loremipsum#gmail.com
Here is my code (inside "components" folder)
import React, { useEffect, useState } from "react";
function Subscribe() {
const [email, setEmail] = useState('')
const [state, setState] = useState('idle')
const [errorMsg, setErrorMsg] = useState(null)
const subscribe = async (e) => {
e.preventDefault()
setState('Loading')
try {
const response = await axios.post('https://myurl.com?email=', { email })
console.log(response)
setState('Success')
setEmail('')
} catch (e) {
console.log(e.response.data.error)
setErrorMsg(e.response.data.error)
setState('Error')
}
}
return (
<div className="container">
<div className="row">
<div className="col-md-7 col-sm-12 col-lg-7 ft-img">
<img src="img/xchanger.png" />
</div>
<div className="col-md-5 col-sm-12 col-lg-5 ft-form">
<form className="row g-3">
<div className="col-12">
<input type="subscribe" className="form-control" id="subscribe2" name="email" type="email" placeholder="Please Subscribe" value={email} onChange={(e) => setEmail(e.target.value)}/>
<button disabled={state === 'Loading'} type="submit" className="btn btn-primary mb-3" onClick={subscribe}> subscribe </button>
</div>
{state === 'Error' && (
<ErrorState className="error-state">{errorMsg}</ErrorState>
)}
{state === 'Success' && (
<SuccessState>Awesome, you've been subscribed!</SuccessState>
)}
</form>
</div>
</div>
</div>
)
}
export default Subscribe

Related

Error message, Warning Cannot update a component (`BrowserRouter`) while rendering a different component

So ive got this error, im guessing its something with my use navigate, but im not shure.
Ive have read alot and searched for the solution but i cant find any way to solve the issue.
The issue only comes after ive have logged in. At the moment i dont have any access token on the backend.
react_devtools_backend.js:4026 Warning: Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at Login (http://localhost:3000/static/js/bundle.js:3571:82)
at div
at LoginPage
at Routes (http://localhost:3000/static/js/bundle.js:129199:5)
at Router (http://localhost:3000/static/js/bundle.js:129132:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:127941:5)
import React from 'react';
import { useRef, useState, useEffect } from 'react'
// import { useContext } from 'react'
//import AuthContext from './context/AuthProvider';
import axios from './api/axios';
const LOGIN_URL = '/login';
const REG_URL = '/newUser'
export default function Login() {
const [authMode, setAuthMode] = useState("signin");
const changeAuthMode = () => {
setAuthMode(authMode === "signin" ? "signup" : "signin");
}
//const { setAuth } = useContext(AuthContext);
const userRef = useRef();
const errRef = useRef();
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const [errMsg, setErrMsg] = useState('');
const [success, setSuccess] = useState(false);
const [register, setRegister] = useState(false);
useEffect(() => {
userRef.current.focus();
}, [])
useEffect(() => {
setErrMsg('');
}, [userName, password])
const handleRegister = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
// set configurations
const RegConfiguration = {
method: "post",
url: REG_URL,
data: {
userName,
password,
},
};
// make the API call
axios(RegConfiguration)
.then((result) => {
setRegister(true);
})
.catch((error) => {
error = new Error();
});
};
///HANDLE Login part.
const handleLogin = async (e) => {
e.preventDefault();
try {
await axios.post(LOGIN_URL,
JSON.stringify({ userName, password }),
{
headers: { 'Content-type': 'application/json' },
withCredentials: false,
}
);
//const token = response?.data?.token;
//setAuth({ userName, password, token })
//console.log(JSON.stringify(respone));
setUserName('');
setPassword('');
setSuccess(true);
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else if (err.response?.status === 400) {
setErrMsg('Missing Username or Password');
} else if (err.response?.status === 401) {
setErrMsg('Unauthorized');
}
else {
setErrMsg('Login Failed');
}
errRef.current.focus();
}
}
const Navigate = useNavigate();
if (authMode === "signin") {
return (
<> {success ? (
Navigate('/authlog')
) : (
<div className="Auth-form-container">
<form className="Auth-form" >
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Not registered yet?{" "}
<span className="link-primary" onClick={changeAuthMode} >
Sign Up
</span>
</div>
<div className="form-group mt-3">
<label>Username </label>
<input
className="form-control mt-1"
id='userName'
ref={userRef}
name="userName"
value={userName}
placeholder="username"
onChange={(e) => setUserName(e.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Password</label>
<input
className="form-control mt-1"
name="password"
type="password"
id='password'
value={password}
placeholder="password"
required
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button
type="submit"
className="btn btn-primary"
onClick={(e) => handleLogin(e)}
>
Logga in
</button>
<p ref={errRef} className={errMsg ? "errmsg" : "offscreen"} aria-live="assertive">{errMsg}</p>
</div>
</div>
</form>
</div>
)}</>
)
}
// "Register page"
return (
<div className="Auth-form-container">
<form className="Auth-form" onSubmit={(e) => handleRegister(e)}>
<div className="Auth-form-content">
<h3 className="Auth-form-title">Sign In</h3>
<div className="text-center">
Already registered?{" "}
<span className="link-primary" onClick={changeAuthMode}>
Go to Sign In
</span>
</div>
<div className="form-group mt-3">
<label>Register Your Username here</label>
<input
className="form-control mt-1"
name="userName"
value={userName}
placeholder="ure username here:"
onChange={(event) => setUserName(event.target.value)}
/>
</div>
<div className="form-group mt-3">
<label>Register Youre password</label>
<input
className="form-control mt-1"
type="password"
name="password"
value={password}
placeholder="ure password here"
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<div className="d-grid gap-2 mt-3">
<button type="submit" className="btn btn-primary" onClick={handleRegister}>
Registera
</button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Now Registered Successfully</p>
) : (
<p className="text-danger">Please register your account here</p>
)}
</div>
</div>
</form>
</div>
);
}

Parsing error: 'return' outside of function

I've recently started maintaining JavaScript code and now i am facing trouble in the returning function in line 39. Can someone please help? I have checked the syntax and can't find anything wrong................................................................???????????????????????????????????????????????????????????????????????
import React, { useState, useEffect} from "react";
import axios from "axios";
import { renderMatches, useNavigate, useParams, } from "react-router-dom";
const Editorg = () => {
let navigate = useNavigate();
const {id} = useParams();
console.log(id);
const [user, setUser] = useState ({
name:"",
poname:"",
type:"",
ostatus:"",
});
const { name, poname, type, ostatus } = user;
const onInputChange = e => {
setUser({...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
};
const onSubmit = async e => {
e.preventDefault();
await axios.put( 'http://localhost:3001/users/${id}' , user);
navigate.push("/");
};
const loadUser = async () =>{
const result = await axios.get('http://localhost:3001/users/${id}', user);
setUser(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h5 className="text-left mb-4"> Edit Organization </h5>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<label> Organization Name </label>
<input type="text" className="form-control" name="name" value={name}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Parent Organization Name </label>
<input type="text" className="form-control" name="poname" value={poname}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Type </label>
<input type="text" className="form-control" name="type" value={type}
onChange={e => onInputChange(e)}
/></div>
<div className="form-group">
<label> Organization Status </label>
<input type="text" className="form-control" name="ostatus" value={ostatus}
onChange={e => onInputChange(e)}
/></div>
<div className="container">
<div className="btn-6">
<button className="btn btn-danger float-right">Update</button>
</div>
</div>
</form>
</div>
</div>
);
}
Around line 26 you are closing the function too early.
useEffect(() => {
loadUser();
}, []);
}; // <- Move this to the very end
const onSubmit = async e => {
</div>
</div>
);
}; // <- Move to here
You mistakly add extra termination of curly bracket
useEffect(() => {
loadUser();
}, []);
}; // <--- remove this

Uncaught (in promise) Error: Response not successful: Received status code 400

I'm getting the following error:
Uncaught (in promise) Error: Response not successful: Received status code 400
ApolloError index.ts:58
error QueryManager.ts:316
notifySubscription module.js:137
onNotify module.js:176
error module.js:229
node_modules bundle.js:87211
notifySubscription module.js:137
onNotify module.js:176
error module.js:229
node_modules bundle.js:87253
iterateObserversSafely iteration.ts:13
error Concast.ts:186
notifySubscription module.js:137
onNotify module.js:176
error module.js:229
node_modules bundle.js:84249
promise callback*./node_modules/ bundle.js:84242
Subscription module.js:190
subscribe module.js:264
complete Concast.ts:213
node_modules bundle.js:87093
Concast Concast.ts:84
node_modules bundle.js:83385
node_modules bundle.js:82782
node_modules bundle.js:82781
step tslib.es6.js:102
verb tslib.es6.js:83
__awaiter tslib.es6.js:76
__awaiter tslib.es6.js:72
node_modules bundle.js:82740
node_modules bundle.js:81070
node_modules bundle.js:84883
onSubmit AddTicketModal.jsx:39
React 23
js index.js:7
factory react refresh:6
Webpack 3
I have 2 modals adding data to a MongoDB DB. One is customers and the other is tickets. The customer part is working, but I'm getting the error with the ticket submit. Any ideas?
Here is my AddTicketModal.jsx
import { useState } from "react";
import { FaListAlt } from "react-icons/fa";
import { useMutation, useQuery } from "#apollo/client";
import { GET_CUSTOMERS } from '../queries/customerQueries';
import { ADD_TICKET } from "../mutations/ticketMutations";
import { GET_TICKETS } from "../queries/ticketQueries";
export default function AddTicketModal() {
const [date, setDate] = useState('');
const [ticketNum, setTicketNum] = useState('');
const [customerId, setCustomerId] = useState('');
const [material, setMaterial] = useState('');
const [tareWeight, setTareWeight] = useState('');
const [grossWeight, setGrossWeight] = useState('');
const [netWeight, setNetWeight] = useState('');
const [notes, setNotes] = useState('');
const [addTicket] = useMutation(ADD_TICKET, {
variables: { date, ticketNum, customerId, material, tareWeight, grossWeight, netWeight, notes },
update(cache, { data: { addTicket} }) {
const { tickets } = cache.readQuery({ query: GET_TICKETS});
cache.writeQuery({
query: GET_TICKETS,
data: { tickets: [...tickets, addTicket] },
});
}
});
// Get Clients for select
const {loading, error, data} = useQuery(GET_CUSTOMERS);
const onSubmit = (e) => {
e.preventDefault();
if (date === "" || ticketNum === "" || customerId === "" || material === "" || tareWeight === "" || grossWeight === "" || netWeight === "" || notes === "") {
return alert("Please fill in all fields");
}
addTicket(date, ticketNum, customerId, material, tareWeight, grossWeight, netWeight, notes);
setDate("");
setTicketNum("");
setCustomerId("");
setMaterial("");
setTareWeight("");
setGrossWeight("");
setNetWeight("");
setNotes("");
};
if(loading) return null;
if(error) return "Something Went Wrong"
return (
<>
{ !loading && !error && (
<>
<button type="button"
className="btn btn-secondary"
data-bs-toggle="modal"
data-bs-target="#addTicketModal">
<div className="d-flex align-items-center">
<FaListAlt className="icon" />
<div>New Ticket</div>
</div>
</button>
{/* <!-- Modal --> */}
<div className="modal fade"
id="addTicketModal"
aria-labelledby="addTicketModalLabel"
aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="addTicketModalLabel">New Ticket</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<form onSubmit={onSubmit}>
<div className="mb-1">
<label className="form-label">Date</label>
<input
type="text"
className="form-control" id="date"
value={date} onChange={ (e) => setDate(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Ticket #</label>
<input
type="text"
className="form-control" id="ticketNum"
value={ticketNum} onChange={ (e) => setTicketNum(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Customer</label>
<input
type="text"
className="form-control" id="customerId"
value={customerId} onChange={ (e) => setCustomerId(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Material</label>
<input
type="text"
className="form-control" id="material"
value={material} onChange={ (e) => setMaterial(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Tare Weight</label>
<input
type="text"
className="form-control" id="tareWeight"
value={tareWeight} onChange={ (e) => setTareWeight(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Gross Weight</label>
<input
type="text"
className="form-control" id="grossWeight"
value={grossWeight} onChange={ (e) => setGrossWeight(e.target.value) }
/>
</div>
<div className="mb-1">
<label className="form-label">Net Weight</label>
<input
type="text"
className="form-control" id="NetWeight"
value={netWeight} onChange={ (e) => setNetWeight(e.target.value) }
/>
</div>
<div className="mb-3">
<label className="form-label">Notes</label>
<textarea
className="form-control" id="notes"
value={notes} onChange={ (e) => setNotes(e.target.value) }>
</textarea>
</div>
<div className="mb-3">
<label className="form-label">Customer</label>
<select id="customerId" className="form-select"
value={customerId} onChange={(e) => setCustomerId(e.target.value)}>
<option value="">Select Customer</option>
{ data.customers.map((customer) => (
<option key={customer.id} value={customer.id}>
{customer.name}
</option>
) )}
</select>
</div>
<button type="submit"
data-bs-dismiss="modal" className="btn btn-primary">Submit
</button>
</form>
</div>
</div>
</div>
</div>
</>
)}
</>
);
}
Here is ticketMutation.js
import { gql } from '#apollo/client';
const ADD_TICKET = gql`
mutation AddTicket(
$date: Date!,
$ticketNum: String!,
$customerId: ID!,
$material: String!,
$tareWeight: Number!,
$grossWeight: Number!,
$netWeight: Number!,
$notes: String!
) {
addTicket(
date: $date
ticketNum: $TicketNum
customerId: $customerId
material: $material
tareWeight: $tareWeight
grossWeight: $grossWeight
netWeight: $netWeight
notes: $notes
) {
id
date
ticketNum
customerId {
name
email
phone
}
material
tareWeight
grossWeight
netWeight
notes
}
}
`
export { ADD_TICKET };
Any help is greatly appreciated!
-N8

Uncaught TypeError: Cannot destructure property when using React context

Hello guys so i tried to make global state so the other page can use the state. The problem is i got an error that says:
Login.js:18 Uncaught TypeError: Cannot destructure property 'emailLog' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
Im doing this because i want the email from user after logged in and pass them to another page so that i can display the logged in user.
App.js:
export const EmailUser = React.createContext();
function App() {
Axios.defaults.withCredentials = true;
const [invoice, setInvoice] = useState("");
const [currency, setCurrency] = useState("IDR");
const [myFile, setMyFile] = useState("");
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
<div className="App">
<BasicExample />
<div className="formInput">
<form method="POST" encType="multipart/form-data" action="http://localhost:3001/upload">
<div className="textUser"></div>
<input
className="inputForm"
defaultValue={emailLog}
type="email"
disabled
name="email"
/>
<input className="inputForm" type="number" placeholder="Invoice No" name="InvoiceNo" />
<input className="inputForm" type="date" name="Invoice_Date" />
<input className="inputForm" type="text" placeholder="Description" name="Description" />
<select
className="selectBox"
name="Currency"
onChange={(e) => {
setCurrency(e.target.value);
}}
>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className="inputForm" type="number" placeholder="Amount" name="Amount" />
<input
className="custom-file-upload"
multiple
type="file"
name="DocumentFile"
onChange={(e) => {
setMyFile(e.target.value);
}}
/>
<button className="btnSubmit">Submit</button>
</form>
</div>
</div>
</EmailUser.Provider>
);
}
export default App;
Login.js
const Login = () => {
let navigate = useNavigate();
const { emailLog, setEmailLog } = useContext(EmailUser);
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault();
Axios.post("http://localhost:3001/login", {
email: emailLog,
password: passwordLog,
}).then((response) => {
console.log(response);
if (response.data.message) {
alert(response.data.message);
} else {
setLoginStatus(response.data[0].email);
alert("Redirecting");
navigate("/home");
}
});
};
console.log(emailLog);
useEffect(() => {
Axios.get("http://localhost:3001/login").then((response) => {
if (response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email);
}
});
});
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">{/* <img src={Background}/> */}</div>
<div className="register-content">
<div className="registerForm">
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user">
<GrMail />
</i>
</div>
<div className="div">
<input
type="email"
className="input"
placeholder="Email"
required
onChange={(e) => {
setEmailLog(e.target.value);
}}
/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock">
<AiFillLock />
</i>
</div>
<div className="div">
<input
type="password"
className="input"
placeholder="Password"
required
onChange={(e) => {
setPasswordLog(e.target.value);
}}
/>
</div>
</div>
Don't have an account ?
<button type="submit" className="btn" onClick={login}>
Login
</button>
</div>
</div>
</div>
</div>
);
};
export default Login;
EmailUser context works only with the components that are children of EmailUser.Provider, and it doesn't seem to be the case for Login component. An easy way is to create a separate component, in some EmailUserProvider.js, like so:
import {createContext, useState} from "react"
export const EmailUser = createContext();
export default function EmailUserProvider({children}) {
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
{children}
</EmailUser.Provider>
);
}
And make it wrap all the components that would consume it. If I assume all my components and routes are rendered in App and want the context to be global, I would do so:
<EmailUserProvider>
<App/>
</EmailUserProvider>

ReactJs: Get data from parent URL and pass it to child component

I am sending a form data from a form in reactjs. Some pre inputs from the user have to be sent altogether with the form. I get that data from the URL of the parent file and the form is in the child component.
Parent url:
http://localhost:3000/uploadlist?phmcy=2
I have to get the phmcy value from the URL. (Here the data have to be passed is '2').
parent component:
import Upload froimportm './Upload'
import axios from "axios";
import { Link, withRouter } from "react-router-dom";
import { useLocation } from 'react-router';
export default function Uploadlist() {
let phmcy = (new URLSearchParams(window.location.search)).get("phmcy")
var myphmcy = JSON.stringify(phmcy);
//const phmcyvalue = new URLSearchParams(this.props.location.search);
//const phmcy = phmcyvalue.get('phmcy')
console.log(myphmcy);
const ordersAPI= (url='https://localhost:44357/api/Orders') => {
return {
fetchAll: () => axios.get(url),
create: newRecord => axios.post(url, newRecord),
update: (id, updateRecord) => axios.put(url + id, updateRecord),
delete: id => axios.delete(url+id)
}
}
const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}
return (
<div className="row">
<div className="jumbotron jumbotron-fluid py-4 "></div>
<div className="container text">
<h1 className="display-4"> Order Register</h1>
</div>
<div className="col-md-4 offset-3">
<Upload
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
Child component: (This is where the form is. I have only included a part)
import React, {useState, useEffect} from 'react';
import myphmcy from './Uploadlist';
//const myphmcy = JSON.stringify(phmcy);
console.log(myphmcy);
const defaultImageSrc = '/images/7.jpg';
const initialFieldValues ={
orderId:0,
dateTime:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customerId:1,
pharmacyId:myphmcy,//data obtaind from the URL have to posted as the pharmacyID when posting.
imageName:'',
imageSrc:'',
imageFile: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageFile = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageFile,
imageSrc : x.target.result
})
}
reader.readAsDataURL(imageFile)
}
else{
setValues({
...values,
imageFile:null,
imageSrc:''
})
}
}
const validate = () => {
let temp = {}
temp.customerName = values.customerName == "" ? false : true;
setErrors(temp)
return Object.values(temp).every(x => x == true)
}
const resetForm = () => {
setValues(initialFieldValues)
document.getElementById('image-uploader').value = null;
}
const handleFormSubmit = e => {
e.preventDefault()
if (validate()){
const formData = new FormData()
formData.append('orderId',values.orderId)
formData.append('dateTime',values.dateTime)
formData.append('status',values.status)
formData.append('status2',values.status2)
formData.append('pharmacyName',values.pharmacyName)
formData.append('customerName',values.customerName)
formData.append('patientName',values.patientName)
formData.append('patientAge',values.patientAge)
formData.append('address',values.address)
formData.append('email',values.email)
formData.append('teleNo',values.teleNo)
formData.append('customerId',values.customerId)
formData.append('pharmacyId',values.pharmacyId)
formData.append('imageName',values.imageName)
formData.append('imageFile',values.imageFile)
addOrEdit(formData, resetForm)
alert("Your file is being uploaded!")
}
}
const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')
return (
<>
<div className="container text-center ">
<p className="lead"></p>
</div>
<form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
<div className="card">
<div className="card-header text-center">Place Your Order Here</div>
<img src={values.imageSrc} className="card-img-top"/>
<div className="card-body">
<div className="form-group">
<input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/>
</div>
<div className="form-group">
<input type="datetime-local" className="form-control" placeholder="Date Time" name="dateTime" value={values.dateTime}
onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className={"form-control" + applyErrorClass('customerName')} placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
</div>
<div className="form-group text-center">
<button type="submit" className="btn btn-light">submit</button>
</div>
</div>
</div>
</form>
</>
)
}
This doesn't work well and I can't post the data. Can some genius help me with this?
Issue
For some reason you import the Uploadlist (the default export/import) and name it myphmcy, save this in the initial state, and then never consume the passed myphmcy prop. This pattern tends to lead to stale state as you need to also handle when the prop values update so you can synchronize the state value.
Solution
Storing passed props is anti-pattern in React, just consume the myphmcy prop directly in the handleFormSubmit submit handler. This ensure you are always using the latest myphmcy props value when submitting the form data.
const handleFormSubmit = e => {
e.preventDefault();
if (validate()) {
const formData = new FormData();
formData.append('orderId', values.orderId);
formData.append('dateTime', values.dateTime);
formData.append('status', values.status);
formData.append('status2', values.status2);
formData.append('pharmacyName', values.pharmacyName);
formData.append('customerName', values.customerName);
formData.append('patientName', values.patientName);
formData.append('patientAge', values.patientAge);
formData.append('address', values.address);
formData.append('email', values.email);
formData.append('teleNo', values.teleNo);
formData.append('customerId', values.customerId);
formData.append('pharmacyId', myphmcy) // <-- use the prop directly
formData.append('imageName', values.imageName);
formData.append('imageFile', values.imageFile);
addOrEdit(formData, resetForm) ;
alert("Your file is being uploaded!");
};
You are getting the myphmcy value from props but setting it outside of the function. So it will set only undefined to the pharmacyId. You need to assign the myphmcy value inside the fnuction.

Categories