form input not resetting with useState - reactjs

I have a react bootstrap number form and state.
I would like to reset hours state to 0 after performing the button click and API POST transaction.
hours state updates just fine for the onChange function where I call setHours() in form and I'm using this strategy to reset form data on other components. Any ideas why I can't get it to work elsewhere after button click (i.e. in my try/catch block)??
const [hours, setHours] = useState(0);
// ...
const handleAddWorkItem = async (sprintId, date, hours) => {
try {
await addWorkItemToAirtable(sprintId, date, hours);
const workItems = await fetchWorkItemsByJobId(sprint.job.id);
setworkItems(workItems);
setHours(0); // not working
} catch (error) {
console.log({ error });
}
};
// ...
<Form>
<Form.Group
className="mb-2"
controlId="addTimeFormEmployee"
>
<Form.Label className="mb-0">
<strong>Employee:</strong>
</Form.Label>
<Form.Select
disabled
defaultValue={sprint.employee.id}
onChange={(e) => {
setEmployee(e.target.value);
}}
aria-label="Select Employee"
>
{employees &&
employees.map((employee) => {
return (
<option key={employee.id} value={employee.id}>
{`${employee.firstName} ${employee.surname}`}
</option>
);
})}
</Form.Select>
</Form.Group>
<Form.Group className="mb-2" controlId="addTimeFormDate">
<Form.Label className="mb-0">
<strong>Date:</strong>
</Form.Label>
<Form.Control
type="text"
onFocus={(e) => (e.target.type = "date")}
onChange={(e) => {
setDate(e.target.value);
}}
defaultValue={date}
placeholder={date}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="addTimeFormHours">
<Form.Label className="mb-0">
<strong>Hours:</strong>
</Form.Label>
<Form.Control
type="number"
defaultValue={0}
onChange={(e) => setHours(parseInt(e.target.value, 10))}
placeholder={0}
min={0}
/>
</Form.Group>
</Form>
<Button
variant="success"
onClick={() => {
handleAddWorkItem(sprint.id, date, hours);
}}
>
Add Time
</Button>
Thank you!

Related

React app hanging when typing on input with onChange state

When I start typing anything in the input fields, the page hangs and nothing gets typed. It was working fine before, it just started happening suddenly. I don't know what went wrong.
I have tried adding onBlur and the problem persists. I tried adding value={registerEmail} in the input fields and the problem still remains as well.
Pleae check :(
import React, {useState} from 'react'
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut
} from 'firebase/auth'
import { Form, Button, Card, Container } from 'react-bootstrap'
import {auth} from '../../services/firebase-config'
export default function SignUp() {
const [registerEmail, setRegisterEmail] = useState("")
const [registerPassword, setRegisterPassword] = useState("")
const [registerConfirmedPassword, setRegisterConfirmedPassword] = useState("")
const [user, setUser] = useState({})
onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser)
})
const register = async (event) => {
event.preventDefault();
try {
const user = await createUserWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const login = async(event) => {
event.preventDefault();
try {
const user = await signInWithEmailAndPassword(auth, registerEmail, registerPassword)
console.log(user)
}
catch(error) {
//accounts that don't exist
console.log(error.message)
}
}
const logout = async(event) => {
try {
await signOut(auth)
}
catch(error) {
console.log(error.message)
}
}
return (
<Container className="d-flex align-items-center justify-content-center w-100">
<Card className='p-3' style={{maxWidth:"400px"}}>
<Card.Body>
<h2 className='text-center mb-4'>Sign Up</h2>
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
</Card.Body>
<div className='w-100 text-center mt-2'>
Already have an account? <Button className='w-100' onClick={(e) => login(e)}>Login</Button>
</div>
<Button onClick={(e) => logout(e)}>Logout</Button>
</Card>
</Container>
)
}
Value attr and Initial state was missing in the form.control
<Form>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control value={registerEmail} type="email" onChange={e => setRegisterEmail(e.target.value)} required />
</Form.Group>
<Form.Group id="password">
<Form.Label>Password</Form.Label>
<Form.Control type="password" value={registerPassword} onChange={e => setRegisterPassword(e.target.value)} required />
</Form.Group>
<Form.Group id="password-confirm">
<Form.Label>Password Confirmation</Form.Label>
<Form.Control type="password" onChange={e => setRegisterConfirmedPassword(e.target.value)} required />
</Form.Group>
{ <Button className='w-100' onClick={(e) => register(e)}>Sign Up</Button>}
</Form>
Example - codesandbox

React Multiselect package is sending [object, Object] instead of key and value

I am trying to pass data in my Django back end from react front end. I am able to pass the data using some Multi-select from react. But the problem is I am sending label and value but when I try to print my data in front end and check the data what it is passing I got the result like [object Object] instead of [mylabel MyValue]
and I just want to pass the option value. I am new to react so don't know much about setState things. Can someone help me to do this?
Or any other easy way to pass multiple data in my API it would be much appreciated like I select HD and SD then in my backend I should get both value.
#This is my react code check the deliveryOption, setDeliveryOption
import axios from "axios";
import React, { useState, useEffect } from 'react'
import { LinkContainer } from 'react-router-bootstrap'
import { Table, Button, Row, Col, Form } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import FormContainer from '../components/FormContainer'
import { MultiSelect } from "react-multi-select-component";
import Select from 'react-select';
const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/create/products/";
const options = [
{ label: "HD 🍇", value: "HD" },
{ label: "SD 🥭", value: "SD" },
{ label: "DP 🍓", value: "DP" },
];
function VendorProductCreate() {
const [file, setFile] = useState(null);
const [name, setName] = useState("");
const [price, setPrice] = useState();
const [discount, setDiscount] = useState();
const [description, setDescription] = useState("");
const [subcategory, setSubcategory] = useState("");
const [countInStock, setCountInStock] = useState();
const [deliveryOption, setDeliveryOption] = useState([]);
// const [selected, setSelected] = useState([]);
const { userInfo } = useSelector((state) => state.userLogin);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", file);
formData.append("name", name);
formData.append("price", price);
formData.append("discount", discount);
formData.append("description", description);
formData.append("subcategory", subcategory);
formData.append("countInStock", countInStock);
formData.append("deliveryOption", deliveryOption);
// formData.append("selected", selected);
const resp = await axios.post(UPLOAD_ENDPOINT, formData, {
headers: {
"content-type": "multipart/form-data",
Authorization: `Bearer ${userInfo.token}`,
},
});
console.log(resp.status)
};
return (
<FormContainer>
<form onSubmit={handleSubmit}>
<br></br>
<Link to='/productlist/vendor'>
<Button
variant='outline-info'>Go Back</Button>
</Link>
<FormContainer>
<br></br>
<h1>Merchant Product Upload</h1></FormContainer>
<br></br>
<br></br>
<Form.Group controlId='name'>
<Form.Label><strong> Product Name </strong> </Form.Label>
<Form.Control
required
type='text'
onChange={(e) => setName(e.target.value)}
value={name}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='subcategory'>
<Form.Label>Choose a Category</Form.Label>
<Form.Select aria-label="Default select example"
required
type='text'
value={subcategory}
onChange={(e) => setSubcategory(e.target.value)}>
<option value="LPG Cylinder">LPG Cylinder</option>
<option value="LPG Gas">LPG Gas</option>
</Form.Select>
</Form.Group>
<br />
<Form.Group controlId='price'>
<Form.Label><strong>Price</strong> </Form.Label>
<Form.Control
required
type='number'
// placeholder='Enter Address'
onChange={(e) => setPrice(e.target.value)}
value={price}
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='discount'>
<Form.Label><strong> Set Discount (Optional) </strong> </Form.Label>
<Form.Control
type='number'
onChange={(e) => setDiscount(e.target.value)}
value={discount}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Group controlId='countInStock'>
<Form.Label><strong> Stock </strong> </Form.Label>
<Form.Control
type='number'
onChange={(e) => setCountInStock(e.target.value)}
value={countInStock}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
<Form.Label><strong style={{marginLeft: 10}}>Product Picture</strong> </Form.Label>
<Form.Control
type='file'
id='image-file'
label='Choose File'
onChange={(e) => setFile(e.target.files[0])}
>
</Form.Control>
<br />
<Form.Group controlId='description'>
<Form.Label><strong> Description </strong> </Form.Label>
<Form.Control
required
type='text'
onChange={(e) => setDescription(e.target.value)}
value={description}
// placeholder='Enter Name'
>
</Form.Control>
</Form.Group>
<br />
{/* <Form.Group controlId='deliveryOption'>
<Form.Label>Choose a Delivery</Form.Label>
<Form.Select aria-label="Default select example"
required
multiple
type='checkbox'
onChange={(e) => setDeliveryOption(e.target.value)}>
<option value="HD">HD</option>
<option value="SD">SD</option>
</Form.Select>
</Form.Group>
<br /> */}
{/* <h1>Select Fruits</h1>
<pre>{JSON.stringify(selected)}</pre> */}
{/* <MultiSelect
options={options}
value={selected}
onChange={setSelected}
labelledBy="Select"
/> */}
<Select
isMulti
name="colors"
options={options}
className="basic-multi-select"
classNamePrefix="select"
value={deliveryOption}
onChange={setDeliveryOption}
/>
<br></br>
<FormContainer><FormContainer><FormContainer>
<Button variant='outline-primary' type="submit" className='btn-sm' >
Upload Product
</Button></FormContainer>
</FormContainer></FormContainer>
</form>
</FormContainer>
);
}
export default VendorProductCreate;
#this is backend code using Django rest
#api_view(['POST'])
#permission_classes([IsVendor])
def vendorCreateProduct(request):
data = request.data
user = request.user.vendor
print(data['deliveryOption'])
print(data['selected'])
product = Product.objects.create(
user=user,
name=data['name'],
old_price = data['price'],
discount = data['discount'],
image = data['avatar'],
countInStock = data['countInStock'],
subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0],
description=data['description'],
delivery_option= DeliveryOption.objects.get_or_create(name=data['deliveryOption'])[0],
)
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
I just want to save some multiple choice field with multiple select option using Django and react if you know any other easy and good approach then share

Why getting too many re-renders?

I have a Calculator component for calculating the exponent of a given base.
My code is as follows:
//Exponential Calculator (Power/Squre-Root/Cube-Root)
const Exponents=()=>{
const [result,setResult]=useState(null);
const [choice,setChoice]=useState("Power");
const [x,setX]=useState(null);
const [n,setN]=useState(null);
useEffect(()=>{
},[choice,x,n,result]);
const calcResult=()=>{
let res=1;
if(choice=="Power")
{
for(var i=1;i<=n;i++)
res*=x;
}
else if(choice=="SquareRoot")
res=Math.sqrt(x);
else
res=Math.cbrt(x);
setResult(res);
}
const handleChange=(e)=>{
reset();
setChoice(e.target.value);
}
function reset(){
setResult(null);
setX(null);
setN(null);
}
const choiceData=()=>{
if(choice==="Power"){
return {
name:"Power",
quantities:["Base","Exponent"],
disabled:false
}
}
else if(choice==="SquareRoot")
{
setN(0.50);
return{
name:"Square-Root",
quantities:["Base","Exponent"],
disabled:true
}
}
else if(choice==="CubeRoot")
{
setN(0.34);
return{
name:"Cube-Root",
quantities:["Base","Exponent"],
disabled:true
}
}
}
return(
<>
<Form>
<Form.Group className="mb-4" controlId="choice">
<Form.Label>Select the type of calculation</Form.Label>
<Form.Control
as="select"
className="select-custom-res"
onChange={(e) => handleChange(e)}
>
<option value="Power">Power</option>
<option value="SquareRoot">Square Root</option>
<option value="CubeRoot">Cube Root</option>
</Form.Control>
</Form.Group>
<Form.Group className="mb-4" controlId="text">
<Form.Text className="text">
<strong>
To find the {choiceData().name}, Enter the following values
</strong>
<br />
</Form.Text>
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>{choiceData().quantities[0]}</Form.Label>
<Form.Control
onChange={(e) => setX(e.target.value)}
type="number"
placeholder={"Enter the Base"}
value={x === null ? "" : x}
/>
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>{choiceData().quantities[1]}</Form.Label>
<Form.Control
onChange={(e) => setN(e.target.value)}
type="number"
placeholder={"Enter the Exponent"}
value={n === null ? "" : n}
disabled={choiceData().disabled}
/>
</Form.Group>
<Form.Group className="mb-4">
<Form.Control
readOnly
type="number"
placeholder={result === null ? "Result" : result + " "}
/>
</Form.Group>
</Form>
<div className="button-custom-grp">
<Button variant="primary" onClick={calcResult}>
Calculate
</Button>
<Button variant="dark" onClick={() => reset()} type="reset">
Reset
</Button>
</div>
</>
)
}
On changing the choice from Power to SquareRoot I get an error:Too many rerenders. Interestingly, when I remove the setState line in the choiceData function,the error vanishes. Although I have used useEffect to prevent re-renders, it's not working.
Issue
You call choiceData in the render return, which should be free of side-effects, like enqueueing state updates. When you call setN in the choiceData function it triggers a rerender, which calls choiceData again, which triggers a rerender... repeat ad nauseam.
Solution
I suggest converting choiceData into a chunk of state, and use an useEffect hook to update it and the n state depending on the choice state. In the render return, instead of calling a function to get a value, i.e. choiceData().quantities[0], you instead just access a property of the new choiceData state, i.e. choiceData.quantities[0].
const Exponents = () => {
const [result, setResult] = useState(null);
const [choice, setChoice] = useState("Power");
const [choiceData, setChoiceData] = useState({});
const [x, setX] = useState(null);
const [n, setN] = useState(null);
useEffect(() => {
if (choice === "Power") {
setChoiceData({
name: "Power",
quantities: ["Base", "Exponent"],
disabled: false
});
} else if (choice === "SquareRoot") {
setN(0.5);
setChoiceData({
name: "Square-Root",
quantities: ["Base", "Exponent"],
disabled: true
});
} else if (choice === "CubeRoot") {
setN(0.34);
setChoiceData({
name: "Cube-Root",
quantities: ["Base", "Exponent"],
disabled: true
});
}
}, [choice]);
useEffect(() => {
// is this effect used for anything?
}, [choice, x, n, result]);
const calcResult = () => {
let res = 1;
if (choice == "Power") {
for (var i = 1; i <= n; i++) res *= x;
} else if (choice == "SquareRoot") res = Math.sqrt(x);
else res = Math.cbrt(x);
setResult(res);
};
const handleChange = (e) => {
reset();
setChoice(e.target.value);
};
function reset() {
setResult(null);
setX(null);
setN(null);
}
return (
<>
<Form>
<Form.Group className="mb-4" controlId="choice">
<Form.Label>Select the type of calculation</Form.Label>
<Form.Control
as="select"
className="select-custom-res"
onChange={(e) => handleChange(e)}
>
<option value="Power">Power</option>
<option value="SquareRoot">Square Root</option>
<option value="CubeRoot">Cube Root</option>
</Form.Control>
</Form.Group>
<Form.Group className="mb-4" controlId="text">
<Form.Text className="text">
<strong>
To find the {choiceData.name}, Enter the following values
</strong>
<br />
</Form.Text>
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>{choiceData.quantities[0]}</Form.Label>
<Form.Control
onChange={(e) => setX(e.target.value)}
type="number"
placeholder={"Enter the Base"}
value={x === null ? "" : x}
/>
</Form.Group>
<Form.Group className="mb-4">
<Form.Label>{choiceData.quantities[1]}</Form.Label>
<Form.Control
onChange={(e) => setN(e.target.value)}
type="number"
placeholder={"Enter the Exponent"}
value={n === null ? "" : n}
disabled={choiceData.disabled}
/>
</Form.Group>
<Form.Group className="mb-4">
<Form.Control
readOnly
type="number"
placeholder={result === null ? "Result" : result + " "}
/>
</Form.Group>
</Form>
<div className="button-custom-grp">
<Button variant="primary" onClick={calcResult}>
Calculate
</Button>
<Button variant="dark" onClick={() => reset()} type="reset">
Reset
</Button>
</div>
</>
);
};

How to add edit button and function in react.js

i want to share this question. So, i have a form which is designed by react-bootstrap. And also use React Hooks and React Function Component. I have a form which is add new form and delete form but i don't do edit form.
This is a return statement
return(
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control ref = {firstname} type="text" placeholder="Name.." />
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control ref = {secondname} type="text" placeholder="Surname.." />
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control ref = {email} type="email" placeholder="E-Mail" />
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control ref = {comment} as="textarea" rows={3} placeholder = "Notes :)"/>
</Form.Group>
<Button className = "btn-lg" onClick={handleSubmit} variant="success" type="submit">Submit</Button>
</Form>
</Col>
</Row>
{Formss}
</Container>
)
And then, These are the function of this return
const Formss = input.map((item , index) =>
{
return(
<Lists key = {index} item = {item} index = {index} deleteFunc={handleDelete}/>
)
}
)
const handleSubmit = (event) => {
event.preventDefault();
const name = firstname.current.value
const surname = secondname.current.value
const mail = email.current.value
const mycomment = comment.current.value
const data = {id:id(),
name : name,
surname : surname,
mail : mail,
mycomment : mycomment}
if(data.name && data.surname && data.mail && data.mycomment){
setInput([...input, data])
firstname.current.value = ""
secondname.current.value = ""
email.current.value = ""
comment.current.value =""
}else{
console.log("oopss")
}
}
I use ref hook for handleSubmit. So, How to add edit button and edit function?
To be able to edit data, and to save it in state you can do it as in provided example. Then in handleSubmit function you can process your data further:
import React from "react";
import { Container, Row, Col, Form, Button } from "react-bootstrap";
const App = () => {
const handleSubmit = (e) => {
e.preventDefault();
console.log(state);
};
const initialState = {
firstname: "",
secondname: "",
email: "",
comment: "",
};
const [state, setState] = React.useState(initialState);
const handleChange = ({ target: { value, name } }) => {
setState({ ...state, [name]: value });
};
return (
<Container>
<Row>
<Col>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
name="firstname"
value={state.firstname}
type="text"
placeholder="Name.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Surname</Form.Label>
<Form.Control
name="secondname"
value={state.secondname}
type="text"
placeholder="Surname.."
onChange={handleChange}
/>
</Form.Group>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
value={state.email}
name="email"
type="email"
placeholder="E-Mail"
onChange={handleChange}
/>
<Form.Text> Please, Enter like "asd#asd.com"</Form.Text>
</Form.Group>
<Form.Group>
<Form.Label>Comment</Form.Label>
<Form.Control
name="comment"
value={state.comment}
as="textarea"
rows={3}
placeholder="Notes :)"
onChange={handleChange}
/>
</Form.Group>
<Button className="btn-lg" variant="success" type="submit">
Submit
</Button>
</Form>
</Col>
</Row>
</Container>
);
};
export default App;

Two Antd forms, one component

I have two antd forms within a single component. The first form is a register form where a user inputs various information (firstname, lastname, email, etc..) The submit button triggers a function to open a modal with another form for them to verify their phone number by generating a code that is texted to them. Once the code is typed and they hit verify, it verifies if it is the correct code - then i would like for it to register the user but I am having difficulties pulling in the values from the first form..
Is there a specific way to go about doing this? I thought maybe I could utilize useState and set the values to component level state but even that didnt work..
form
<Form
layout="vertical"
name="register-form"
initialValues={initialValues}
onFinish={handleVerification}
>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="firstName"
label="First Name"
rules={rules.firstName}
hasFeedback
>
<Input placeholder="Enter First Name" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="lastName"
label="Last Name"
rules={rules.lastName}
hasFeedback
>
<Input placeholder="Enter Last Name" />
</Form.Item>
</Col>
</Row>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="phone"
label="Phone Number"
rules={rules.phone}
hasFeedback
>
<Input placeholder="Enter Phone Number" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item name="city" label="City" rules={rules.city} hasFeedback>
<Select placeholder="Select City">
<Option value="Lancaster, PA">Lancaster, PA</Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item
name="email"
label="Email Address"
rules={rules.email}
hasFeedback
>
<Input placeholder="Enter Email Address" />
</Form.Item>
<Form.Item
name="password"
label="Password"
rules={rules.password}
hasFeedback
>
<Input.Password placeholder="Enter Password" />
</Form.Item>
<Form.Item
name="confirmPassword"
label="Confirm Password"
rules={rules.confirm}
hasFeedback
>
<Input.Password placeholder="Confirm Password" />
</Form.Item>
<Form.Item name="tos" valuePropName="checked">
<Checkbox>
I agree to the <Link to="/">Terms of Service</Link> and{' '}
<Link to="/">Privacy Policy</Link>.
</Checkbox>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Register
</Button>
</Form.Item>
</Form>
<Modal
title="Account Verification"
centered
visible={modal}
onOk={() => setModal(false)}
onCancel={() => setModal(false)}
>
<p>
To finish registering, please enter the verification code we just sent
to your phone. If you didn't receive a code, make sure your entered
phone number is correct and sign up again. Your code will expire upon
closing this popup.
</p>
<Form layout="vertical" name="verify-phone-form" onFinish={onSubmit}>
<Form.Item name="enteredCode" label="Verify">
<Input placeholder="Enter Code" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Verify
</Button>
</Form.Item>
</Form>
</Modal>
handleVerification
const handleVerification = async (values) => {
const { phone, email } = values;
setModal(true);
try {
const response = await postRegisterCheckDuplicate({ email, phone });
if (response.data.success) {
switch (response.data.message) {
case 0:
try {
const response = await dispatch(
attemptRegisterVerify({ to: phone })
);
console.log('handleVerification: ', response.message);
if (response.success) {
setGeneratedCode(response.message);
} else {
console.log(response.message);
}
} catch (error) {
console.log(error);
}
break;
case 1:
console.log('Email Address already in use.');
break;
case 2:
console.log('Phone number already in use.');
break;
case 3:
console.log('Email and Phone in use.');
break;
}
} else {
console.log(response.data.message);
}
} catch (error) {
console.log(error);
}
};
onSubmit
const onSubmit = (values) => {
const { enteredCode } = values;
if (generatedCode === enteredCode) {
try {
console.log('values :', values);
// dispatch(attemptRegister(values));
} catch (error) {
console.log(error);
}
} else {
console.log('Verification code incorrect');
}
};
You can create a form instance (hooks) and reference it to the first form so you can use the api of the instance. You can check more here antd FormInstance
const [registerForm] = Form.useForm();
const handleSubmit = (values) => {
const { enteredCode } = values;
console.log(registerForm.getFieldsValue());
//output is the values in the first form
};
<Form form={registerForm} layout="vertical" onFinish={handleVerification}>
...
</Form>
I created a small version of your work. See working code here:
You can also check this one antd control between forms

Resources