retrieve checkbox value to modify state with redux - reactjs

We are developing the functionality to create an account. We manage to retrieve the new data from the different fields (last name, first name, etc.) to modify the state. However, we are stuck on one aspect. When creating the user's account, the latter has the possibility of using checkboxes in order to choose his preferred technologies (JS, PHP etc...) BUT we are unable to retrieve the value of the following checkboxes if they are checked or not.
Here is the code for our component:
import {
Header as HeaderSui, Container, Form, Checkbox,
} from 'semantic-ui-react';
import { useSelector, useDispatch } from 'react-redux';
import { changeFieldNewLogin } from '../../actions/newUser';
function User() {
const dispatch = useDispatch();
const emailUser = useSelector((state) => state.newUser.email);
const passwordUser = useSelector((state) => state.newUser.password);
const nameUser = useSelector((state) => state.newUser.name);
const surnameUser = useSelector((state) => state.newUser.surname);
const department = useSelector((state) => state.newUser.department);
const descriptionUser = useSelector((state) => state.newUser.description);
const tag = useSelector((state) => state.newUser.tag);
return (
<div>
<HeaderSui textAlign="center" as="h1">The Dev Corner</HeaderSui>
<Container>
<Form>
<Form.Group widths="equal">
<Form.Input
value={nameUser}
fluid
label="Nom"
placeholder="Nom..."
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'name');
dispatch(action);
}}
/>
<Form.Input
value={surnameUser}
fluid
label="Prenom"
placeholder="Prenom..."
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'surname');
dispatch(action);
}}
/>
</Form.Group>
<Form.Group widths="equal">
<Form.Input
value={emailUser}
fluid
label="Email"
placeholder="Email.."
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'email');
dispatch(action);
}}
/>
<Form.Input
value={passwordUser}
type="password"
fluid
label="Password"
placeholder="Password...."
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'password');
dispatch(action);
}}
/>
</Form.Group>
<Form.Group widths="equal">
<Form.Field
value={department}
label="Département"
control="select"
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'department');
dispatch(action);
}}
>
<option value="Choississez votre département">Choisissez votre département</option>
<option value="Iles de france">Iles de france</option>
<option value="Bouches du rhones">Bouches du rhones</option>
</Form.Field>
</Form.Group>
<Form.Group widths="equal">
<h3>Choisissez vos technologies préférées</h3>
<Checkbox
label="JS"
value={tag}
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'tag');
dispatch(action);
}}
/>
<Checkbox
value={tag}
label="PHP"
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'tag');
dispatch(action);
}}
/>
</Form.Group>
<Form.TextArea
value={descriptionUser}
label="Description"
placeholder="Votre description..."
onChange={(event) => {
const action = changeFieldNewLogin(event.target.value, 'description');
dispatch(action);
}}
/>
<Form.Checkbox label="I agree to the Terms and Conditions" />
<Form.Button primary>Créer mon compte</Form.Button>
</Form>
</Container>
</div>
);
}
export default User;

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

CRUD firestore React function delete()

I am trying to do the delete function for a CRUD with React & Firestore, I already manage to eliminate it, the problem is the way I get the ID since it always deletes the record that is lower in the table.
function delete()
const handleDelete = async(id) =>{
/* setData([]); */
console.log(id)
try {
/* await db.collection('empleado').doc(id).delete(); */
} catch (error) {
console.log(error)
}
}
get ID
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().dleted,doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => ({id: doc.id})))
})
},[]);
onClick function button parameter
{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id) }>
Delete
</button>
);
}
}
},
this is my console.log()
(4) [{…}, {…}, {…}, {…}]
0: {id: "48DIVsf7NLc5ux5vfH76"}
1: {id: "B3Jnpmmtipmi3IwvxKzs"}
2: {id: "cSPnc9lDpgvWNDXsXhfo"}
3: {id: "rLzJuLFfanXTSArA9fd2"}
length: 4
[[Prototype]]: Array(0)
this happen when press button delete (any row button delete), i want upload a image of my table.
Component
import React,{useEffect} from 'react';
import "../../../css/employee.css";
import Dashboard from '../Dashboard';
import { db } from '../../../firebase';
import MUIDataTable from "mui-datatables";
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
function Employee(){
const [data,setData] = React.useState([]);
const[id,setId]=React.useState('');
const[dleted,setDleted]=React.useState('');
const handleDelete = async(id) =>{
/* setData([]); */
console.log(id)
try {
/* await db.collection('empleado').doc(id).delete(); */
} catch (error) {
console.log(error)
}
}
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => ({id: doc.id, data:doc.data()})))
})
},[]);
const columns =[{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id)}>
Delete
</button>
);
}
}
},
"TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];
const options = {
filterType: 'checkbox',
};
return(
<div id="employ">
<div><Dashboard /></div>
<hr/>
<div style={{marginLeft:'18em'}}>
<MUIDataTable
title={"EMPLEADOS"}
data={data}
columns={columns}
options={options}
/>
</div>
</div>
);
}
export default Employee;
Try this:
<button onClick={ ()=>handleDelete(tableMeta.rowData[0])}> //you have to put the index of your id here
Delete
</button>
SOLUCIONADO
COMPONENT Employee
import React,{useEffect} from 'react';
import "../../../css/employee.css";
import Dashboard from '../Dashboard';
import { db } from '../../../firebase';
import MUIDataTable from "mui-datatables";
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
function Employee(){
const [data,setData] = React.useState([]);
const[id,setId]=React.useState('');
const[dleted,setDleted]=React.useState('');
const [tipoDoc, setTipoDoc] = React.useState('');
const [doc, setDoc] = React.useState('');
const [lugarExp, setLugarExp] = React.useState('');
const [nombre, setNombre] = React.useState('');
const [direccion, setDireccion] = React.useState('');
const [telefono, setTelefono] = React.useState('');
const [email, setEmail] = React.useState('');
const [cargo, setCargo] = React.useState('');
const [rh, setRh] = React.useState('');
const [eps, setEps] = React.useState('');
const [tiempoPago, setTiempoPago] = React.useState('');
const [sueldo, setSueldo] = React.useState('');
const handleSubmit = async (e) => {
e?.preventDefault();
setData([]);
db.collection("empleado").add({
tipoDoc: tipoDoc,
doc: doc,
lugarExp: lugarExp,
nombre: nombre,
direccion: direccion,
telefono: telefono,
email: email,
cargo: cargo,
rh:rh,
eps:eps,
tiempoPago:tiempoPago,
sueldo:sueldo,
}).then(() => {
}).catch((error) => {
alert(error.message)
});
}
const handleDelete = async(id,index) =>{
setData([]);
let parse = '';
let parse2='';
console.log(id);
console.log(index);
parse = parseInt(index);
for (let i = 0; i < id.length; i++) {
if(i === parse ){
const element = id[i];
console.log("element",typeof(element))
parse2 = element;
console.log("B3Jnpmmtipmi3IwvxKzs"==parse2)
await db.collection("empleado").doc(parse2).delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
}
}
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => (doc.id)))
})
},[]);
const columns =[{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id,`${tableMeta.rowIndex}`)}>
Delete
</button>
);
}
}
},
, "TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];
const options = {
filterType: 'checkbox',
};
return(
<div id="employ">
<div><Dashboard /></div>
<hr/>
<div style={{marginLeft:'18em'}}>
<MUIDataTable
title={"EMPLEADOS"}
data={data}
columns={columns}
options={options}
/>
</div>
<hr />
<hr /><br /><br /><br/>
<Form id="form-contact">
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridState">
<Form.Label>Tipo documento</Form.Label>
<Form.Select defaultValue="-" value={tipoDoc} onChange={e => { setTipoDoc(e.target.value) }}>
<option>-</option>
<option>Tarjeta Identidad</option>
<option>Cedula Ciudadania</option>
<option>Cedula Extranjeria</option>
</Form.Select>
</Form.Group>
<Form.Group as={Col} controlId="formGridEmail">
<Form.Label>Documento</Form.Label>
<Form.Control type="text" value={doc} onChange={e => { setDoc(e.target.value) }} placeholder="0000000" />
</Form.Group>
<Form.Group as={Col} controlId="formGridPassword">
<Form.Label>Lugar expedicion</Form.Label>
<Form.Control type="text" value={lugarExp} onChange={e => { setLugarExp(e.target.value) }} placeholder="municipio/departamento" />
</Form.Group>
</Row>
<Form.Group className="mb-3" controlId="formGridAddress1">
<Form.Label>Nombre</Form.Label>
<Form.Control type="text" placeholder="name" value={nombre} onChange={e => { setNombre(e.target.value) }} />
</Form.Group>
<Form.Group className="mb-3" controlId="formGridAddress2">
<Form.Label>Direccion</Form.Label>
<Form.Control placeholder="Cra - #" value={direccion} onChange={e => { setDireccion(e.target.value) }} />
</Form.Group>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Telefono </Form.Label>
<Form.Control value={telefono} onChange={e => { setTelefono(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Email </Form.Label>
<Form.Control value={email} onChange={e => { setEmail(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Cargo </Form.Label>
<Form.Control value={cargo} onChange={e => { setCargo(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridState">
<Form.Label>RH</Form.Label>
<Form.Select defaultValue="-" value={rh} onChange={e => { setRh(e.target.value) }}>
<option>-</option>
<option>A+</option>
<option>AB+</option>
<option>O+</option>
</Form.Select>
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>EPS </Form.Label>
<Form.Control value={eps} onChange={e => { setEps(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Tiempo pago </Form.Label>
<Form.Control value={tiempoPago} onChange={e => { setTiempoPago(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Sueldo </Form.Label>
<Form.Control value={sueldo} onChange={e => { setSueldo(e.target.value) }} />
</Form.Group>
</Row>
<Form.Group className="mb-3" id="formGridCheckbox" style={{textAlign:'left'}}>
<Form.Check type="checkbox" label="Acepto términos del servicio y tratamiento de datos." />
</Form.Group>
<button type="button" class="btn btn-secondary btn-lg" onClick={()=>handleSubmit()} >Agregar</button>
</Form>
<hr/>
<hr/>
</div>
);
}
export default Employee;

Internal server error when attempting to register user in React/Redux app

I have a database on AtlasDB cloud service. In my React application, I want my code to save the data from the form below to be saved in the database, however I get internal server error (500) when I make a post request. What could be the problem here? The code of the React component is as follows:
import React, { useState, useEffect } from "react";
//state for form fields
import { Link } from "react-router-dom";
import { Form, Button, Row, Col } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import Message from "../components/Message";
import Loader from "../components/Loader";
import FormContainer from "../components/FormContainer";
import { register } from "../actions/userActions";
const RegisterScreen = ({ location, history }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [message, setMessage] = useState(null);
const dispatch = useDispatch();
const userRegister = useSelector((state) => state.userLogin);
const { loading, error, userInfo } = userRegister;
const redirect = location.search ? location.search.split("=")[1] : "/";
const goToLoginScreen = () => {
history.goBack();
}
useEffect(() => {
if (userInfo) {
history.push(redirect);
}
}, [history, userInfo, redirect]);
const submitHandler = (e) => {
e.preventDefault();
//dispatch register
if(password !== confirmPassword){
setMessage('Passwords do not match');
} else {
goToLoginScreen();
dispatch(register(name, email, password));
}
};
return (
<FormContainer>
<h1>Sign Up</h1>
{message && <Message variant="danger">{message}</Message>}
{error && <Message variant="danger">{error}</Message>}
{loading && <Loader />}
<Form onSubmit={submitHandler}>
<Form.Group controlId="name">
<Form.Label>Name </Form.Label>
<Form.Control
type="name"
placeholder="Enter name"
value={name}
onChange={(e) => setName(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="email">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="confirmPassword">
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type="password"
placeholder="Confirm password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Button type="submit" variant="primary">
Register
</Button>
</Form>
<Row className="py-3">
<Col>
Have an account?{" "}
<Link to={redirect ? `/login?redirect=${redirect}` : "/login"}>
Login
</Link>
</Col>
</Row>
</FormContainer>
);
};
export default RegisterScreen;
It is very difficult to me to localize the error in code, whether it is a question of front-end or back-end. The user is not saved in the remote database.

How to add validation in Product add Form c- react component

I am doing Form for add product to firebase, but each click on the submit button, although it already has data or not, it still can add in Firebase. I would like to add validation to this case. How could I do that. I would like all file input cannot be left blank, and text file is always text not the number
const ProductForm = ({
products,
createProductRequest,
fetchProductRequest,
loading,
type }) => {
const [values, setValues] = useState({
image: "",
name: "",
price: 0,
description: "",
categoty: "",
});
const [imageAsFile, setImageAsFile] = useState();
useEffect(() => {
if (Object.keys(products).length) {
setValues(products);
}
}, [products]);
useEffect(() => {
if (type === "CREATE_PRODUCT_SUCCESS") {
fetchProductRequest();
}
}, [fetchProductRequest, type]);
const handleInputChange = (event) => {
// Create new product to update
const newPropdudct = {
...values,
[event.target.name]: event.target.value,
};
// Update new product for value
setValues(newPropdudct);
};
const handleFileChange = (event) => {
const image = event.target.files[0]
setImageAsFile(imageAsFile => (image))
console.log(image);
}
const onSave = () => {
createProductRequest(values, imageAsFile);
};
if (loading) {
return (
<Container>
<Loading />
</Container>
);
}
return (
<Container className="product-form">
<Form>
<Form.Group>
<Form.Group>
<Form.File
id="image"
label="Image choose"
value={values.image.name}
onChange={handleFileChange}
/>
</Form.Group>
</Form.Group>
<Form.Group controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter product name"
value={values.name}
name="name"
onChange={handleInputChange}
>
</Form.Control>
</Form.Group>
<Form.Group controlId="categories">
<Form.Label>Categories</Form.Label>
<Form.Control
as="select"
name="category"
value={values.category}
onChange={handleInputChange}
>
{CATEGORIES.map((category, index) => (
<option key={index}>{category.name}</option>
))}
</Form.Control>
</Form.Group>
<Form.Group controlId="price">
<Form.Label>Price</Form.Label>
<Form.Control
type="number"
placeholder="Enter product price"
value={values.price}
name="price"
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group controlId="description">
<Form.Label>Description</Form.Label>
<Form.Control
as="textarea"
rows="3"
name="description"
value={values.description}
onChange={handleInputChange}
/>
</Form.Group>
<Button btnText="Submit" size="btn-md" handleClick={onSave} />
</Form>
</Container>
);
};
export default ProductForm;
You may start by adding the required attribute to each form control for basic HMTL5 validation.
For more advanced validation logic, you can have this as your onSave content:
const onSave = (event) => {
let invalid = [];
['name', 'description', 'category'].forEach(key => {
if (values[key].match(/[0-9]+/))
invalid.push(key);
});
if (values.name.trim() === '')
invalid.push('name');
if (invalid.length !== 0) {
event.preventDefault();
// Whatever you want to do when the content is invalid
} else {
createProductRequest(values, imageAsFile);
}
};
With this snippet, you have the invalid fields in the invalid array variable.
You can also customize the validation logic.

Resources