Submitting dynamically created form to database in reactJS - reactjs

I am trying to insert the values through this dynamic form but I am only able to insert just one entry (even though I enter multiple forms) and the values that are getting inserted are 0 (in the database as well).
I am passing the index still I am not getting the desired output. The list looks like this:
List of the entered details
The previous entry was entered manually.
This is the CODE through which I submit values.
import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
import { useNavigate, useParams } from 'react-router-dom'
import RoomInfoService from '../services/RoomInfoService';
const RoomInfo = () => {
const [shared_no] = useState();
const [no_of_rooms] = useState();
const [rent_per_month] = useState();
const [vacancy] = useState();
const [total_capacity] = useState();
const [pg_fid, setpgfid] = useState();H
let handleChange = (i, e) => {
let newFormValues = [...formValues]; /** makes a copy of the current form values and assign it to newFormValues **/
newFormValues[i][e.target.name] = e.target.value;
setFormValues(newFormValues);
}
const navigate = useNavigate();
let addFormFields = () => {
setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}])
};
let removeFormFields = (i) => {
let newFormValues = [...formValues];
newFormValues.splice(i, 1);
setFormValues(newFormValues)
}
const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }])
/*const [settotal_no_of_rooms] = useState('1');
const [setrooms_entered] = useState('1');
const getTotalCapacity = () => {
return formValues.reduce((total,element) => {
return total + Number(element.shared_no) * Number(element.no_of_rooms);
}, 0);
};*/
const resetForm = () => setFormValues([{shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: ""}]);
const Total_no_of_rooms_entered = () => {
return formValues.reduce((total, element) => {
return total + Number(element.no_of_rooms);
}, 0);
};
const saveRoomInfo = (e) =>{
e.preventDefault();
const roominfo = [...formValues];
RoomInfoService.createRoomInfo(roominfo).then((response) => {
console.log(response.data);
navigate('/listroominfo');
}).catch(error =>{
console.log(error);
})
}
return (
<>
<div className='heading'>
<h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
</div>
<form>
<div className="form-inline" style={{ marginBottom: '50px' }}>
{/*<label>Total of Rooms: </label>
<input type="number" name="total_no_of_rooms" style={{ width: '90px' }} onClick={(e) => settotal_no_of_rooms(e.target.value)} defaultValue={1} /> */}
<label>Rooms Entered:</label>
<div><input type="number" name="rooms_entered" value={Total_no_of_rooms_entered()} readOnly></input></div>
</div>
</form>
<div>
<form>
{formValues.map((element, index) => (
<div className="form-inline" key={index} style={{ borderBottom: '1px solid black' }}>
<label>Sharing Number</label>
<select id="shared_no" name="shared_no" title="no of shared rooms" value={element.shared_no || ""} onChange={e => handleChange(index, e)} >
<option value="">---Select---</option>
<option value="1">Single Sharing</option>
<option value="2">Two Bed Sharing</option>
<option value="3">Three Bed Sharing</option>
<option value="4">Four Bed Sharing</option>
<option value="5">Five Bed Sharing</option>
</select>
<label> No of Rooms:</label>
<input type="number" style={{ width: '60px' }} name="no_of_rooms" value={element.no_of_rooms || ""} onChange={e => handleChange(index, e)}></input>
<label> Rent per month:</label>
<input type="number" style={{ width: '100px' }} name="rent_per_month" value={element.rent_per_month || ""} onChange={e => handleChange(index, e)}></input>
<label> Total Capacity:</label>
<input type="number" style={{ width: '80px' }} name="total_capacity" value={element.total_capacity} onChange={e => handleChange(index, e)}></input>
<label> Vacancy:</label>
<input type="number" style={{ width: '50px' }} name="vacancy" value={element.vacancy || ""} onChange={e => handleChange(index, e)}></input>
{
index ?
<button type="button" className="button-remove" onClick={() => removeFormFields(index)}><ImBin size={20}/></button>
: null
}
</div>
))}
<div className="button-section">
<button className="button" type="button" onClick={() => addFormFields()}>Add</button>
<button className="button" type="button" onClick={resetForm}>Reset</button>
<button className="button" type="submit" onClick={(e) => saveRoomInfo(e)}>Submit</button>
</div>
</form>
</div>
</>
)
}
export default RoomInfo
Reference of Dynamic Form
The issue is while I am fetching the data from the form. But I can't figure it out. Thank you.

Related

Dynamically Calculating values in React JS Form using Hooks

I am working on PG finder application and I want that on the owner side on adding the shared number he/she automatically gets the total capacity of the rooms (i.e like we have 2 sharing and total no of rooms available are 3 so total capacity/ beds will be 6)
So I want that column to generate value dynamically
Image Reference for query
As you can see the totalcapacity value is getting copied for the next dynamic generated form field also. I want them to be separate.
import React, { useEffect, useState } from "react";
import './roominfo.css';
import { ImBin } from 'react-icons/im';
const RoomInfo = () => {
let handleChange = (i, e) => {
let newFormValues = [...formValues]; /** makes a copy of the current form values and assign it to newFormValues **/
newFormValues[i][e.target.name] = e.target.value;
setFormValues(newFormValues);
}
let addFormFields = () => {
setFormValues([...formValues, { shared_no: "", no_of_rooms: "", rent_per_month: "", vacancy: "",total_capacity: 0}])
};
let removeFormFields = (i) => {
let newFormValues = [...formValues];
newFormValues.splice(i, 1);
setFormValues(newFormValues)
}
const [formValues, setFormValues] = useState([{ shared_no: "", no_of_rooms: "", rent_per_month: "", total_capacity: "", vacancy: "" }])
const [total_no_of_rooms, settotal_no_of_rooms] = useState('1');
const [rooms_entered, setrooms_entered] = useState('');
const getTotalCapacity = () => {
return formValues.reduce((total,element) => {
return total + Number(element.shared_no) * Number(element.no_of_rooms);
}, 0);
};
const Total_no_of_rooms_entered = () => {
return formValues.reduce((total, element) => {
return total + Number(element.no_of_rooms);
}, 0);
};
useEffect(() => {
if (rooms_entered > total_no_of_rooms) {
window.alert("No more rooms can be added");
}
},)
return (
<>
<div className='heading'>
<h1 style={{ marginBottom: '50px' }}>Enter Your PG Room Details</h1>
</div>
<form>
<div className="form-inline" style={{ marginBottom: '50px' }}>
<label>Total of Rooms: </label>
<input type="number" name="total_no_of_rooms" style={{ width: '90px' }} onClick={(e) => settotal_no_of_rooms(e.target.value)} defaultValue={1} />
<label>Rooms Entered:</label>
<div><input type="number" name="rooms_entered" value={Total_no_of_rooms_entered()} onClick={(e) => setrooms_entered(e.target.value)} readOnly></input></div>
</div>
</form>
<div>
<form>
{formValues.map((element, index) => (
<div className="form-inline" key={index} style={{ borderBottom: '1px solid black' }}>
<label>Sharing Number</label>
<select id="shared_no" name="shared_no" title="no of shared rooms" value={element.shared_no || ""} onChange={e => handleChange(index, e)} >
<option value="">---Select---</option>
<option value="1">Single Sharing</option>
<option value="2">Two Bed Sharing</option>
<option value="3">Three Bed Sharing</option>
<option value="4">Four Bed Sharing</option>
<option value="5">Five Bed Sharing</option>
</select>
<label> No of Rooms:</label>
<input type="number" name="no_of_rooms" value={element.no_of_rooms || ""} onChange={e => handleChange(index, e)}></input>
<label> Rent per month:</label>
<input type="number" style={{ width: '100px' }} name="rent_per_month" value={element.rent_per_month || ""} onChange={e => handleChange(index, e)}></input>
<label> Total Capacity:</label>
<input type="number" style={{ width: '50px' }} name="total_capacity" value={getTotalCapacity()} onChange={e => handleChange(index, e)}></input>
<label> Vacancy:</label>
<input type="number" style={{ width: '50px' }} name="vacancy" value={element.vacancy || ""} onChange={e => handleChange(index, e)}></input>
{
index ?
<button type="button" className="button remove" onClick={() => removeFormFields(index)}><ImBin /></button>
: null
}
</div>
))}
<div className="button-section">
<button className="button add" type="button" onClick={() => addFormFields()}>Add</button>
<button className="button submit" type="submit">Submit</button>
</div>
</form>
</div>
</>
)
}
export default RoomInfo
This is the code. Can you please help me with how to solve it.Thank you

How to Validate Minimum Age Greater & Equal to 18 Reactjs

For the SignUp page I need to validate age is equal to or greater than 18. I have attempted using similar examples but all require me to install a dependency. I am looking for a way to achieve the desired results through React. My code is as follows
signup.jsx
import React from "react";
import { useState, useRef } from "react";
import { BsFillInfoCircleFill } from "react-icons/bs";
import Tooltip from "react-bootstrap/Tooltip";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
import { Link } from "react-router-dom";
import Alert from 'react-bootstrap/Alert'
import { UserAuth } from "../../AuthContext";
const Password = (props) =>
{
const [passwordShown, setPasswordShown] = useState(false);
const togglePassword = () => {
setPasswordShown(!passwordShown);
}
return(
<div className="input-group w-75 mb-5">
<input
type= {passwordShown ? 'text' : 'password'}
ref = {props.myRef}
className="form-control shadow-none"
placeholder="PSU1>OSU!"
aria-describedby="button-addon2"
></input>
<button onClick={togglePassword}>Show Password</button>
</div>
);
}
const SignUpPopup = (props) => {
//input fields
const firstName = useRef("");
const lastName = useRef("");
const email = useRef("");
const DOB = useRef("");
const password = useRef("");
const passwordConfirm = useRef("");
const [checked1, setChecked1] = useState(false);
const [checked2, setChecked2] = useState(false);
var errorMessage = ""
//change handlers
const handleChange1 = () => { setChecked1(!checked1) } ;
const handleChange2 = () => { setChecked2(!checked2) } ;
const [error, setError] = useState("");
const {createUser} = UserAuth();
//IMPROVE THE CHECKING OF THE FORM
function checkSignUp(){
var success = true
if (firstName.current.value === ""){
success = false
errorMessage += "Invalid first name\n"
}
if (lastName.current.value === ""){
success = false
errorMessage += "Invalid last name\n"
}
if (email.current.value === ""){
success = false
errorMessage += "Invalid email\n"
}
if (password.current.value === "" ){
success = false
errorMessage += "Invalid password\n"
}
if (!(passwordConfirm.current.value === password.current.value ) ){
success = false
errorMessage += "Passwords do not match\n"
}
return success;
}
async function addUserToDatabase(uid){
fetch("URL",{
method: "POST",
headers: { "Content-Type": "application/json"},
body: uid
})
}
async function handleSignup() {
setError("")
//if res == true, success, else failure and trigger alert
var res = checkSignUp();
if(res){
//authenticate
try{
await createUser(email.current.value, password.current.value);
const {user} = UserAuth();
addUserToDatabase(user.uid);
props.handleClose();
props.signupNextFunc();
}
catch(e){
errorMessage += "Invalid email or password"
setError(errorMessage)
}
}
}
const changeToLogin = ()=>{
props.handleClose()
props.loginFunc()
}
return (
<div className="popup-box">
<div className="box">
<div className="upperwrapper">
<span className="close-icon" onClick={props.handleClose}>
x
<input
type="text"
ref={firstName}
className="form-control shadow-none"
placeholder="Ben"
aria-describedby="button-addon2"
></input>
</div>
{/* LAST NAME INPUT */}
<p style={{ fontSize: "20px", marginTop: "15px" }}>
Last Name<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {lastName}
className="form-control shadow-none"
placeholder="Dover"
aria-describedby="button-addon2"
></input>
</div>
{/* EMAIL INPUT */}
<p style={{ fontSize: "20px", marginTop: "45px" }}>
Email<span className="required-field"></span>
</p>
<div className="input-group w-75 mb-5">
<input
type="text"
ref = {email}
className="form-control shadow-none"
placeholder="bendover#email.com"
aria-describedby="button-addon2"
></input>
</div>
<div className="d-flex bd-highlight mb-3 example-parent">
<p style={{ fontSize: "20px", marginTop: "10px" }}>
Date of Birth<span className="required-field"></span>
</p>
<div style={{ display: 'block', marginLeft: "-3px", marginTop: "-8px" }}
className="align-self-center p-2 bd-highlight col-example">
<OverlayTrigger
delay={{ hide: 450, show: 300 }}
overlay={(props) => (
<Tooltip {...props}>
Please provide your date of birth to validate...
</Tooltip>
)}
placement="right"
>
<div><BsFillInfoCircleFill /></div>
</OverlayTrigger>
</div>
</div>
<div className="input-group w-75 mb-5">
<input
type="date"
ref={DOB}
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
></input>
</div>
)
};
export default SignUpPopup;
Any help or guidance to the right path is greatly appreciated!
You can validate age on onChange of input
const onChange = (e) => {
const currentYear = new Date().getFullYear();
const year = e.target.value.split("-")[0];
const age = currentYear - year;
if (age < 18) setError("Invalid age");
}
<input
type="date"
className="form-control shadow-none"
placeholder="mm/dd/yyyy"
aria-describedby="button-addon2"
onChange={onChange}
/>

How i can implement redux saga concept in login page react

Here how can i implement this login page using Redux saga concept. I also attached my codesandbox link below. Please provide any ideas to implement using redux saga concept.
For what purpose we mainly use redux saga concepts in react. Please provide any articles for learning redux saga.
https://codesandbox.io/s/inspiring-rain-olm7wx?file=/src/components/Login.jsx
import React from "react";
import { connect } from "react-redux";
import { loginAction } from "../actions/loginAction";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const passwordValidator = /(?=.*[a-z])/;
function Login(props) {
let navigate = useNavigate();
const isLogin = useSelector((state) => state.login.isLogin);
useEffect(() => {
if (isLogin) {
navigate("/");
}
}, [isLogin]);
const [state, setState] = useState({
email: "",
password: "",
emailAddressError: "",
passwordError: "",
isLogin: false,
isFormSubmitted: false
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (event) => {
event.preventDefault();
var data = {
email: state.email,
password: state.password
};
let formFileds = ["email", "password"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) {
setState((prev) => ({ ...prev, isFormSubmitted: true }));
const dispatch = props.dispatch;
dispatch(loginAction.login(data));
} else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "password") isValid = validatePassword();
return isValid;
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value.trim() === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
const validatePassword = () => {
let passwordError = "";
const value = state.password;
if (value.trim() === "") passwordError = "Password is required";
else if (!passwordValidator.test(value))
passwordError = "Password contains small character only";
setState((prev) => ({ ...prev, passwordError }));
return passwordError === "";
};
return (
<div>
<div>
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Login</h5>
<form className="form" onSubmit={handleSubmit}>
<div class="form-group">
<label class="form-label">
<b>Email</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="text"
class="form-control"
label="email"
name="email"
value={state.email}
onChange={handleChange}
placeholder="email"
onBlur={handleBlur}
autoComplete="off"
/>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
</div>
<div class="Login_formGroup__3wtgQ form-group">
<label class="form-label">
<b>Password</b>
</label>{" "}
<span style={{ color: "red" }}> *</span>
<input
type="password"
class="form-control"
variant="outlined"
id="outlined-basic"
label="password"
name="password"
value={state.password}
onChange={handleChange}
placeholder="password"
onBlur={handleBlur}
autoComplete="off"
/>
{state.passwordError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.passwordError}
</div>
)}
</div>
<div class="d-flex justify-content-between align-items-center mt-5">
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
>
<b>LOGIN</b>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
const mapStateToProps = (state) => {
return {
token: state.login.token
};
};
export default connect(mapStateToProps)(Login);

Im facing error in firstname ,lastname required in my code. It is not showing those errors

Here for email, password and confirm password error messages are showing but for firstname, phone number and lastname the error is not showing. How can I find out what that error is?
For email when I click on that field and do not give any value, it is showing an error and the same thing for firstname.
import React from "react";
import { useState } from "react";
const emailValidator = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function Register(props) {
const [state, setState] = useState({
email: "",
emailAddressError: "",
firstName: "",
firstNameError: ""
});
const handleChange = (event) => {
const { name, value } = event.target;
setState((prev) => ({ ...prev, [name]: value }));
return;
};
const handleBlur = (event) => {
const { name } = event.target;
validateField(name);
return;
};
const handleSubmit = (e) => {
e.preventDefault();
let formFileds = ["email", "firstName"];
let isValid = true;
formFileds.forEach((field) => {
isValid = validateField(field) && isValid;
});
if (isValid) setState((prev) => ({ ...prev, isFormSubmitted: true }));
else setState((prev) => ({ ...prev, isFormSubmitted: false }));
return state.isFormSubmitted;
};
const validateField = (name) => {
let isValid = false;
if (name === "email") isValid = validateemail();
else if (name === "firstName") isValid = validatefirstName();
return isValid;
};
const validatefirstName = () => {
let firstNameError = "";
const value = state.firstName;
if (value.trim() === "") firstNameError = "First Name is required";
setState((prev) => ({ ...prev, firstNameError }));
return firstNameError === "";
};
const validateemail = () => {
let emailAddressError = "";
const value = state.email;
if (value === "") emailAddressError = "Email Address is required";
else if (!emailValidator.test(value))
emailAddressError = "Email is not valid";
setState((prev) => ({ ...prev, emailAddressError }));
return emailAddressError === "";
};
return (
<div id="__next">
<div class="no-gutters row" style={{ height: "100vh" }}>
<div class="d-flex flex-column justify-content-center align-items-center h-100 col-12 col-md-6">
<div class="container">
<div class="d-flex justify-content-center row">
<div class="col-auto col-lg-8">
<h5 class="fw-bold mb-5">Sign Up</h5>
<form class="w-100">
<div class="d-flex form-group">
<div class="flex-fill mr-5">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
First Name
</label>
<input
name="firstName"
value={state.firstName}
onChange={handleChange}
maxLength="20"
class="form-control"
placeholder="First Name"
/>
</div>
{state.firstNameError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.firstNameError}
</div>
)}
</div>
<div class="form-group">
<span style={{ color: "red" }}> *</span>
<label for="exampleEmail" class="fw-bold">
Email
</label>
<input
name="email"
class="form-control"
value={state.email}
onChange={handleChange}
placeholder="Email"
onBlur={handleBlur}
autoComplete="off"
/>
</div>
{state.emailAddressError && (
<div className="errorMsg" style={{ color: "red" }}>
{state.emailAddressError}
</div>
)}
<div class="d-flex justify-content-between align-items-center mt-5">
<a
href="/login"
style={{ textDecoration: "none", color: "#bd744c" }}
>
{" "}
</a>
<button
class="btn "
style={{ backgroundColor: "#bd744c", color: "white" }}
onSubmit={handleSubmit}
>
<b>SIGN UP</b>
</button>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<div class="d-none d-md-inline-block h-100 Register_backgroundImage__2j-eI col-sm-6"></div>
</div>
</div>
);
}
// export default Register;
export default Register;
You forgot to call onBlur={handleBlur} in firstName and I have made small changes in your code:
Now it will show errors when you click on submit.

Form in React + Formik + Material Ui (dialog + stepper)

My form worked 2 days ago when i didn't implement material UI with dialog and stepper. All the data was sent to the database.
Now i did it, It doesn't want to send at all, i don't even have a mistake in the console or network tab in dev tools. You'll find below at first what that doesnt work. In second where that work.
Thanks a lot in advance.
import { Formik, Form, Field } from 'formik';
import { makeStyles, useTheme } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import Dialog from '#material-ui/core/Dialog';
import DialogContent from '#material-ui/core/DialogContent';
import DialogTitle from '#material-ui/core/DialogTitle';
import MobileStepper from '#material-ui/core/MobileStepper';
import KeyboardArrowLeft from '#material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '#material-ui/icons/KeyboardArrowRight';
import axios from 'axios';
import Tools from './Tools';
import Technos from './Technos';
import Clients from './Clients';
import Managers from './Managers';
import Collaborators from './Collaborators';
const validate = (values) => {
const errors = {};
if (values.project_name === '') {
errors.project_name = 'Please choose at least a project name';
} else if (values.end_date < values.start_date) {
errors.end_date = 'The end date has to be after the start date';
}
return errors;
};
const useStyles = makeStyles(() => ({
steps: {
maxWidth: 400,
flexGrow: 1,
},
ModalDialog: {
height: '682px',
width: '683px',
},
}));
const CreateProject = () => {
const [tools, setTools] = useState([]);
const [toolsSelected, setToolsSelected] = useState([]);
const [newTool, setNewTool] = useState('');
const [technos, setTechnos] = useState([]);
const [technosSelected, setTechnosSelected] = useState([]);
const [newTechno, setNewTechno] = useState('');
const [clients, setClients] = useState([]);
const [clientSelected, setClientSelected] = useState();
const [newClient, setNewClient] = useState('');
const [collaborators, setCollaborators] = useState([]);
const [collaboratorsSelected, setCollaboratorsSelected] = useState([]);
const [managers, setManagers] = useState([]);
const [manager, setManager] = useState();
const [projectNameExist, setProjectNameExist] = useState(false);
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const [activeStep, setActiveStep] = React.useState(0);
const submitting = (values, actions) => {
const data = { ...values };
data.ClientId = parseInt(clientSelected, 10);
data.Tools = toolsSelected;
data.Technos = technosSelected;
data.ManagerId = manager;
data.Collaborators = collaboratorsSelected;
axios({
method: 'post',
url: 'http://localhost:5000/api/projects',
data,
})
.then(() => actions.setSubmitting(false))
// .then(() => history.push('/'))
.catch((err) => {
if (err.response.status === 409) {
setProjectNameExist(true);
}
});
};
useEffect(() => {
axios
.get('http://localhost:5000/api/tools')
.then((res) => res.data)
.then((data) => setTools(data));
}, []);
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<Formik
validate={validate}
validateOnChange={false}
validateOnBlur={false}
onSubmit={submitting}
initialValues={{
project_name: '',
start_date: undefined,
end_date: undefined,
teams_link: '',
number_sprints: undefined,
duration_sprints: undefined,
description: '',
time_budget_type: undefined,
project_type: undefined,
signed: undefined,
chance_winning: 0,
}}
>
{({ errors }) => (
<Form id="formCreateProject">
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Create Project
</Button>
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog">
<DialogTitle id="form-dialog">Create a project</DialogTitle>
<div className={classes.ModalDialog}>
<DialogContent>
{activeStep === 0 ? (
<div style={{ visibility: activeStep !== 0 ? 'hidden' : '' }}>
<label htmlFor="project_name">Project Name:</label>
<Field
type="text"
id="project_name"
name="project_name"
placeholder="Your project name"
/>
{errors.project_name && <p>{errors.project_name}</p>}
{projectNameExist ? <p style={{ color: 'white' }}>This project name already exist</p> : ''}
<label htmlFor="project_type">Project type:</label>
<Field name="project_type" id="project_type" as="select">
<option value="">--Please choose an option--</option>
<option value="Development">Development</option>
<option value="Design">Design</option>
<option value="Cybersecurity">Cybersecurity</option>
<option value="Cloud">Cloud</option>
</Field>
<Clients
clients={clients}
clientSelected={clientSelected}
newClient={newClient}
setNewClient={setNewClient}
setClientSelected={setClientSelected}
setClients={setClients}
/>
<Managers
managers={managers}
setManagers={setManagers}
setManager={setManager}
/>
<label htmlFor="signed">Is the contract signed?</label>
<Field name="signed" id="signed" as="select">
<option value="">--Please choose an option--</option>
<option value="0">False</option>
<option value="1">True</option>
</Field>
</div>
) : '' }
{activeStep === 1 ? (
<div style={{ visibility: activeStep !== 1 ? 'hidden' : '' }}>
Step 2
<label htmlFor="description">Description:</label>
<Field
type="text"
id="description"
name="description"
placeholder="Short description of the project, what was sold, what are the expectations of the client?"
rows="4"
cols="50"
/>
<label htmlFor="teams_link">Teams link:</label>
<Field
type="text"
id="teams_link"
name="teams_link"
placeholder="Your teams link"
/>
</div>
) : '' }
{activeStep === 2 ? (
<div style={{ visibility: activeStep !== 2 ? 'hidden' : '' }}>
ddsdsds
</div>
) : '' }
{activeStep === 3 ? (
<div style={{ visibility: activeStep !== 3 ? 'hidden' : '' }}>
<Tools
tools={tools}
toolsSelected={toolsSelected}
newTool={newTool}
setNewTool={setNewTool}
setToolsSelected={setToolsSelected}
setTools={setTools}
/>
<Technos
technos={technos}
technosSelected={technosSelected}
newTechno={newTechno}
setNewTechno={setNewTechno}
setTechnosSelected={setTechnosSelected}
setTechnos={setTechnos}
/>
</div>
) : '' }
{activeStep === 4 ? (
<div style={{ visibility: activeStep !== 4 ? 'hidden' : '' }}>
Step 5
<Collaborators
collaborators={collaborators}
setCollaborators={setCollaborators}
collaboratorsSelected={collaboratorsSelected}
setCollaboratorsSelected={setCollaboratorsSelected}
/>
<button type="submit">
Create
</button>
</div>
) : '' }
</DialogContent>
</div>
<MobileStepper
variant="dots"
steps={5}
position="static"
activeStep={activeStep}
className={classes.steps}
nextButton={(
<Button size="small" onClick={handleNext} disabled={activeStep === 4}>
Next
{theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</Button>
)}
backButton={(
<Button size="small" onClick={handleBack} disabled={activeStep === 0}>
{theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />}
Back
</Button>
)}
/>
</Dialog>
</Form>
)}
</Formik>
);
};
export default CreateProject;```
The previous component where that worked is here:
```import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { Formik, Form, Field } from 'formik';
import axios from 'axios';
import Tools from './Tools';
import Technos from './Technos';
import Clients from './Clients';
import Managers from './Managers';
import Collaborators from './Collaborators';
const validate = (values) => {
const errors = {};
if (values.project_name === '') {
errors.project_name = 'Please choose at least a project name';
} else if (values.end_date < values.start_date) {
errors.end_date = 'The end date has to be after the start date';
}
return errors;
};
const NewProject = () => {
const history = useHistory();
const [tools, setTools] = useState([]);
const [toolsSelected, setToolsSelected] = useState([]);
const [newTool, setNewTool] = useState('');
const [technos, setTechnos] = useState([]);
const [technosSelected, setTechnosSelected] = useState([]);
const [newTechno, setNewTechno] = useState('');
const [clients, setClients] = useState([]);
const [clientSelected, setClientSelected] = useState();
const [newClient, setNewClient] = useState('');
const [collaborators, setCollaborators] = useState([]);
const [collaboratorsSelected, setCollaboratorsSelected] = useState([]);
const [managers, setManagers] = useState([]);
const [manager, setManager] = useState();
const [projectNameExist, setProjectNameExist] = useState(false);
const submitting = (values, actions) => {
const data = { ...values };
data.ClientId = parseInt(clientSelected, 10);
data.Tools = toolsSelected;
data.Technos = technosSelected;
data.ManagerId = manager;
data.Collaborators = collaboratorsSelected;
axios({
method: 'post',
url: 'http://localhost:5000/api/projects',
data,
})
.then(() => actions.setSubmitting(false))
.then(() => history.push('/'))
.catch((err) => {
if (err.response.status === 409) {
setProjectNameExist(true);
}
});
};
useEffect(() => {
axios
.get('http://localhost:5000/api/tools')
.then((res) => res.data)
.then((data) => setTools(data));
}, []);
return (
<div id="newProject">
<Formik
validate={validate}
validateOnChange={false}
validateOnBlur={false}
onSubmit={submitting}
initialValues={{
project_name: '',
start_date: undefined,
end_date: undefined,
teams_link: '',
number_sprints: undefined,
duration_sprints: undefined,
description: '',
time_budget_type: undefined,
project_type: undefined,
signed: undefined,
chance_winning: 0,
}}
>
{({ errors }) => (
<Form id="formCreateProject">
<h1 style={{ color: 'white' }}>Create a project</h1>
<label htmlFor="project_name">Project Name:</label>
<Field
type="text"
id="project_name"
name="project_name"
placeholder="Your project name"
/>
{errors.project_name && <p>{errors.project_name}</p>}
{projectNameExist ? <p style={{ color: 'white' }}>This project name already exist</p> : ''}
<Clients
clients={clients}
clientSelected={clientSelected}
newClient={newClient}
setNewClient={setNewClient}
setClientSelected={setClientSelected}
setClients={setClients}
/>
<Managers managers={managers} setManagers={setManagers} setManager={setManager} />
<label htmlFor="start_date">Start date:</label>
<Field
type="date"
id="start_date"
name="start_date"
min="1000-01-01"
max="3000-12-31"
/>
<label htmlFor="end_date">End date:</label>
<Field
type="date"
id="end_date"
name="end_date"
min="1000-01-01"
max="3000-12-31"
/>
{errors.end_date && <p>{errors.end_date}</p>}
<label htmlFor="teams_link">Teams link:</label>
<Field
type="text"
id="teams_link"
name="teams_link"
placeholder="Your teams link"
/>
<label htmlFor="number_sprints">Number of sprints:</label>
<Field type="number" id="number_sprints" name="number_sprints" />
<label htmlFor="duration_sprints">
Duration of sprints (in weeks):
</label>
<Field
type="number"
id="duration_sprints"
name="duration_sprints"
/>
<label htmlFor="description">Description:</label>
<Field
type="text"
id="description"
name="description"
placeholder="Short description of the project, what was sold, what are the expectations of the client?"
rows="4"
cols="50"
/>
<label htmlFor="time_budget_type">Budget type:</label>
<Field name="time_budget_type" id="time_budget_type" as="select">
<option value="">--Please choose an option--</option>
<option value="Time and material">Time and material</option>
<option value="Time Package">Time Package</option>
</Field>
<label htmlFor="project_type">Project type:</label>
<Field name="project_type" id="project_type" as="select">
<option value="">--Please choose an option--</option>
<option value="Development">Development</option>
<option value="Design">Design</option>
<option value="Cybersecurity">Cybersecurity</option>
<option value="Cloud">Cloud</option>
</Field>
<label htmlFor="signed">Is the contract signed?</label>
<Field name="signed" id="signed" as="select">
<option value="">--Please choose an option--</option>
<option value="0">False</option>
<option value="1">True</option>
</Field>
<label htmlFor="chance_winning">
Chance to win the contract (max 100%):
</label>
<Field
type="number"
id="chance_winning"
name="chance_winning"
min="0"
max="100"
/>
<Tools
tools={tools}
toolsSelected={toolsSelected}
newTool={newTool}
setNewTool={setNewTool}
setToolsSelected={setToolsSelected}
setTools={setTools}
/>
<Technos
technos={technos}
technosSelected={technosSelected}
newTechno={newTechno}
setNewTechno={setNewTechno}
setTechnosSelected={setTechnosSelected}
setTechnos={setTechnos}
/>
<Collaborators
collaborators={collaborators}
setCollaborators={setCollaborators}
collaboratorsSelected={collaboratorsSelected}
setCollaboratorsSelected={setCollaboratorsSelected}
/>
<button type="submit">
Create
</button>
</Form>
)}
</Formik>
</div>
);
};
export default NewProject;```

Resources