React app hanging when typing on input with onChange state - reactjs

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

Related

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

Conditional statement to show registration success message is showing the error message even when successful?

I wasn't sure how to phrase the title but basically, I am following a tutorial to create a login/registration and I am currently trying to display a message indicating whether the registration attempt was successful or not.
Here is my Register.js
import React, { useState } from 'react';
import { Form, Button } from 'react-bootstrap';
import axios from "axios";
export default function Register() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [register, setRegister] = useState(false);
const handleSubmit = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
//set configuration
const configuration = {
method: "post",
url: "https://nodejs-mongodb-auth-app-learn.herokuapp.com/register",
data: {
email,
password,
},
};
// API call
axios(configuration)
.then((result) => {
console.log(result);
setRegister=(true);
})
.catch((error) => {
error= new Error;
})
};
return (
<>
<h2>Register</h2>
<Form onSubmit={(e)=>handleSubmit(e)}>
{/* email */}
<Form.Group controlId="formBasicEmail">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter email"
/>
</Form.Group>
{/* password */}
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
/>
</Form.Group>
{/* submit button */}
<Button
variant="primary"
type="submit"
onClick={(e)=>handleSubmit(e)}
>
Register
</Button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Registered Successfully</p>
) : (
<p className="text-danger">You Are Not Registered</p>
)}
</Form>
</>
)
};
The successful registration will log on the console, but either setRegister is not updating register to true, or my conditional statement is incorrect in some way?
It always shows "You Are Not Registered".
The correct way to ser an state using useState hook is:
e.g
const [register, setRegister] = useState(false);
setRegister(true)

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 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;

How to create login and redirect to another page after success?

How to create login and redirect to another page after success? i trying to below code but not working anyone can help me ? i don't know how to login and redirect to home page i am created below login page but i don't know how to check and redirect
import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import { Redirect } from "react-router";
import "./Login.css";
const Login = (props) =>{
const[redirect,setRedirect]=useState();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
function validateForm() {
return email.length > 0 && password.length > 0;
}
function handleSubmit(event) {
event.preventDefault();
if (!(username === '123456' && password === '123456')) {
return setError(true);
}
setRedirect("/");
}
return(
{redirect?<Redirect to={redirect}/>:null}
<div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="Login">
<Form onSubmit={handleSubmit}>
<Form.Group size="lg" controlId="email">
<Form.Label>Email</Form.Label>
<Form.Control
autoFocus
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group size="lg" controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button block size="lg" type="submit" disabled={!validateForm()}>
Login
</Button>
</Form>
</div>
</div>
)
}
export default Login
Check below its working
LoginForm.js
import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import "./Login.css";
function LoginForm({Login, error}) {
const [details, setDetails] = useState({email:"", password:""});
const submitHandler = e =>{
e.preventDefault();
Login(details);
}
return(
<div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="login">
<h2 style={{textAlign:'center'}}>Login</h2>
<Form onSubmit={submitHandler}>
<Form.Group size="lg" controlId="email">
<Form.Label>Email</Form.Label>
<input
className="form-control"
autoFocus
type="email"
name="email"
id="email"
onChange={e => setDetails({...details, email: e.target.value})}
value={details.email}
/>
</Form.Group>
<Form.Group size="lg" controlId="password">
<Form.Label>Password</Form.Label>
<input
className="form-control"
type="password"
name="password"
id="password"
onChange={e => setDetails({...details, password: e.target.value})}
value={details.password}
/>
</Form.Group>
<Button block size="lg" type="submit">
Login
</Button>
</Form>
</div>
</div>
)
}
export default LoginForm
App.js
import React, { useState } from 'react';
import './App.css';
import LoginForm from './LoginForm';
function App() {
const adminUser = {
email: "admin#admin.com",
password: "admin123"
}
const [user, setUser] = useState({email:""});
const [error, setError] =useState("");
const Login = details =>{
console.log(details);
if(details.email == adminUser.email && details.password == adminUser.password){
console.log("Logged in");
setUser({
email:details.email
})
}else{
console.log("User Password Wrong!");
}
}
const Logout = () =>{
setUser({email: ""})
}
return (
<div className="App">
{(user.email !="") ? (
<div className="welcome">
<h2>Welcome, <span>{user.email}</span></h2>
<button onClick={Logout}>Logout</button>
</div>
):(
<LoginForm Login={Login} error={error} />
)}
</div>
);
}
export default App;
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
You can easily approach it with window.location.href as below.
const App = (props) =>{
const[redirect,setRedirect]=useState();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
function validateForm() {
return email.length > 0 && password.length > 0;
}
function handleSubmit(event) {
event.preventDefault();
if (!(email=== '123456' && password === '123456')) {
console.log("Error")
}
window.location.href = "/";
}
return(
<div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="Login">
<Form onSubmit={handleSubmit}>
<Form.Group size="lg" controlId="email">
<Form.Label>Email</Form.Label>
<Form.Control
autoFocus
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group size="lg" controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button block size="lg" type="submit" disabled={!validateForm()}>
Login
</Button>
</Form>
</div>
</div>
)
}
export default App;

Resources