What mean "form submitting canceled"? - reactjs

Get warning in console when trying to submit login form (form submission canceled because the form is not connected). If deleting if (isAuthed) return <Redirect to="/additem" />; my form became are connected. In other issues people say 'replace type of button from submit to button'. It doesn't work. How can I connect form?
export function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [isAuthed, setIsAuthed] = useState(false);
console.log(isAuthed);
function onChangeUsername(e) {
setUsername(e.target.value)
}
function onChangePassword(e) {
setPassword(e.target.value)
}
function getToken() {
const token = Date.now().toString();
if (username && password) {
localStorage.setItem('userToken', JSON.stringify(token));
setIsAuthed(true)
}
}
//if (isAuthed) return <Redirect to="/additem" />;
return (
<div className="col-md-12">
<div className="card card-container">
<form onSubmit={getToken} noValidate>
<span className="fas fa-sign-in-alt"/>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control"
name="username"
value={username}
onChange={onChangeUsername}
placeholder="Login"
required
/>
<div className="invalid-feedback">
Wrong username
</div>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
name="password"
value={password}
onChange={onChangePassword}
placeholder="Password"
required
/>
<div className="invalid-feedback">
Wrong password
</div>
</div>
<div className="form-group">
<button className="btn btn-primary" type="submit">
Submit form
</button>
</div>
</form>
</div>
</div>
)
}

First of your form is submitting except you're doing one thing which is not getting you your expected results. You will need to prevent the default behavior with form submission. Preventing the default behavior will prevent the page from reloading which is the normal behavior with form submission.
function getToken(event) {
event.preventDefault();
const token = Date.now().toString();
if (username && password) {
localStorage.setItem('userToken', JSON.stringify(token));
setIsAuthed(true)
//you can then redirect here. Example
//pass in a props then props.history.push("/additem");
}
}

Related

Inability to input text in my forms input boxes in react.js

I am unable to type within my label boxes, this has got me incredibly confused as I'm trying to make a simple username/password registration form that logs the data into a database, however this isn't really possible without having the ability to input data. Wondering if I can get some assistance.
import axios from "axios";
import React, { useState } from "react";
export default function Home() {
const [user, setUser] = useState({
username: "",
password: "",
});
const { username, password} = user;
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
const onSubmit = async (e) => {
e.preventDefault();
await axios.post("http://localhost:8080/user", user);
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow">
<h2 className="text-center m-4">Register User</h2>
<form onSubmit={(e) => onSubmit(e)}>
<div className="mb-3">
<label htmlFor="Username" className="form-label">
Username
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your username"
name="Username"
value={username}
onChange={(e) => onInputChange(e)}
/>
</div>
<div className="mb-3">
<label htmlFor="Password" className="form-label">
Password
</label>
<input
type={"text"}
className="form-control"
placeholder="Enter your Password"
name="Password"
value={password}
onChange={(e) => onInputChange(e)}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Submit
</button>
</form>
</div>
</div>
</div>
);
}
I looked at the code but i’m just incredibly confused, it looks fine to me
This is because you don't have the correct names in your input.
Replace Password by password and Username by username.
It has to be the same as in your state.

How to pass data from page to another page

Hello guys i have a react project made with react, node, express, and mysql. The thing is i want to get email from login and pass to home page. How do i do that, i dont want to use useParams() because the user can input their email in the link, i want to avoid that. Is there any way to do that and if you can, can you give code example.
Login
const Login = () => {
let navigate = useNavigate();
const [emailLog, setEmailLog] = useState("");
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault()
Axios.post("http://localhost:3001/login" , {
email: emailLog,
password: passwordLog
}).then((response)=> {
console.log(response)
if(response.data.message) {
alert((response.data.message))
} else{
setLoginStatus(response.data[0].email)
alert("Redirecting")
navigate("/home")
}
})
}
useEffect(() => {
Axios.get('http://localhost:3001/login').then((response)=> {
if(response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email)
}
})
})
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">
{/* <img src={Background}/> */}
</div>
<div className="register-content">
<div className='registerForm'>
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user"><GrMail /></i>
</div>
<div className="div">
<input type="email" className="input" placeholder='Email' required
onChange={(e)=> {
setEmailLog(e.target.value)
}}/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock"><AiFillLock /></i>
</div>
<div className="div">
<input type="password" className="input" placeholder='Password' required
onChange={(e)=> {
setPasswordLog(e.target.value)
}}/>
</div>
</div>
Don't have an account ?
<button type='submit' className='btn' onClick={login} data={emailLog}>Login</button>
</div>
</div>
</div>
</div>
)
}
export default Login
App.js
function App() {
const [invoice, setInvoice] = useState("");
const [date, setDate] = useState ("");
const [currency, setCurrency] = useState ("IDR");
const [ myFile, setMyFile] = useState("");
const [test, setTest] = useState("anjay#anjay.com");
Axios.defaults.withCredentials = true;
return (
<div className="App">
<BasicExample />
<div className='formInput'>
<form method='POST' encType='multipart/form-data' action='http://localhost:3001/upload'>
<div className='textUser'>
<h1>{props.data}</h1>
</div>
<input className='inputForm' defaultValue={test} type="email" disabled name='email' />
<input className='inputForm' type="number" placeholder='Invoice No' name='InvoiceNo' />
<input className='inputForm' type="date" name='Invoice_Date' />
<input className='inputForm' type="text" placeholder='Description' name='Description' />
<select className='selectBox' name='Currency' onChange={(e)=> {
setCurrency(e.target.value);
}}>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className='inputForm' type="number" placeholder='Amount' name='Amount'/>
<input className='custom-file-upload' multiple type="file" name="DocumentFile" onChange={(e)=> {
setMyFile(e.target.value);
}} />
<button className='btnSubmit'>Submit</button>
</form>
</div>
</div>
);
}
export default App;
I think props drilling should solve it.
example
Login Component
function Login({email, setEmail}){
// you need to update state email here
}
Home or App.js
function App(){
const [email, setEmail] = useState("");
// here you should pass the props to login component,
// so you have the ability to set or asign the email state
<Login email={email} setEmail={setEmail} />
}
If you want to send data tp one page, you can use state with navigate.
navigate("/home", {state: { email: emailLog }})
you can get data from your home component like,
{props.location.state.email}

My react form is not submitting correctly

i have a problem with my react's form.
If I click twice on the submit button then at this moment, the form submits correctly and sends my various information to the database.
Where is the problem ?
import React, { useState } from 'react';
import axios from 'axios';
const Register = () => {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const onSubmit = (e) => {
e.preventDefault();
setUsername(document.querySelector(".usernameInput").value);
setPassword(document.querySelector(".passwordInput").value);
const user = {
username: username,
password: password
}
axios.post('http://localhost:5000/users/add', user)
.then(res => console.log(res.data));
console.log("lancement du formulaire");
}
return (
<div>
<h1>TEST Form</h1>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input required type="text" className="usernameInput" />
</div>
<div className="form-group">
<label>Password</label>
<input required type="password" />
</div>
<div className="form-group">
<input type="submit" value="Create User" className="btn btn-primary" className="passwordInput" /> </div>
</form>
</div>
)
}
export default Register;
Thanks .
useState is asynchronous just like setState in class components. You can't update the state on one line and assume it's already changed on the next one. You'll likely use the unchanged state.
When you create the user object, the state is not yet updated.
You need to click twice on the submit button because:
on the first click you set the username and password states' value to the input value but as the state is not updated, you send the user objects with empty properties
on the second click (when the state is updated) you can send the user object, as the user object contains the state values
The following should work (though I would recommend not to use it):
const onSubmit = (e) => {
e.preventDefault();
const user = {
username: document.querySelector('.usernameInput').value,
password: document.querySelector('.passwordInput').value,
};
axios
.post('http://localhost:5000/users/add', user)
.then((res) => console.log(res.data));
console.log('lancement du formulaire');
};
But why do you use states username and password if you never use them? If you've already added the states to store the input values, you can update them on changes and submit them on form submit:
const Register = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const onSubmit = (e) => {
e.preventDefault();
const user = {
username,
password,
};
axios
.post('http://localhost:5000/users/add', user)
.then((res) => console.log(res.data));
console.log('lancement du formulaire');
};
return (
<div>
<h1>TEST Form</h1>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
required
type="text"
className="usernameInput"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
required
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="submit"
value="Create User"
className="btn btn-primary"
className="passwordInput"
/>{' '}
</div>
</form>
</div>
);
};

ReactJS Form Input - can't get a "const" variable in validation function

I'm trying to compare two inputs - password and password confirmation. For each input I have a function where I return alert.
Solution that I have is from this tutorial in Register Page.
I'm new in ReactJS and don't understand everything, but here is my code sample:
<Form onSubmit={handleRegister} ref={form}>
{!successful && (
<div>
<div className="form-group">
<label htmlFor="password"></label>
<Input
type="password"
className="form-control"
placeholder="Password"
name="password"
value={password}
onChange={onChangePassword}
validations={[required, vpassword]}
/>
</div>
<div className="form-group">
<label htmlFor="passConfirm"></label>
<Input
type="password"
placeholder="Confirm password"
className="form-control"
name="passConfirm"
value={passConfirm}
onChange={onChangePassConfirm}
validations={[required, vPassConfirm]}
/>
</div>
<div className="form-group">
<button className="btn btn-primary btn-block" id="registerButton">Register</button>
</div>
</div>
)}
{message && (
<div className="form-group">
<div
className={ successful ? "alert alert-success" : "alert alert-danger" }
role="alert"
>
{message}
</div>
</div>
)}
<CheckButton style={{ display: "none" }} ref={checkBtn} />
</Form>
and there I pass this function:
const vPassConfirm = (value) => {
console.log(password);
if (value != password) {
return (
<div className="alert alert-danger" role="alert">
The password does not match!
</div>
);
}
In this vPassConfirm I want to compare my variables
const[password, setPassword] = useState("");
const[passConfirm, setPassConfirm] = useState("");
but in:
console.log(password)
I get only null or something like that - its empty. I cant get the variable.
My question is - is there a possibility to get this variable 'password' inside vPassConfirm function?
EDIT
const onChangePassword = (e) => {
const password = e.target.value;
setPassword(password);
};
const onChangePassConfirm = (e) => {
const passConfirm = e.target.value;
setPassConfirm(passConfirm);
};
there is a declaration above:
const form = useRef();
const checkBtn = useRef();
I use react-valiadtion
After reviewing the documentation for react-validation, it seems you can use the additional arguments passed to validation functions to check other form values.
Validation functions accept (at least) the arguments: value, props, components. Values for other inputs can be found in the components argument.
Here's how you can update your vPassConfirm function so that it checks the current value of the password input:
const vPassConfirm = (value, props, components) => {
if (value !== components['passConfirm'][0].value) {
return (
<div className="alert alert-danger" role="alert">
The password does not match!
</div>
)
}
};
If you want a validation function that would work for either the password or passConfirm input, you could change the conditional line to:
components['password'][0].value !== components['passConfirm'][0].value

How to store object In Cookie in React using Hooks

I am working on a React project In my project I have a scenario to store object in Cookie.
This is my code Login.js
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(data)
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
When I click submit button data will print in console. I have to store that in cookie
So what is the best way to store data object in Cookie
You can save the cookie in document.cookie. But you need to save the data as a string.
You could parse the whole object with JSON.parse, or the more elegant way is to use the specific attributes.
Cookies
But be aware that it is not save to store passwords in cookies.
Try this:
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
document.cookie = `email=${data.email}`;
document.cookie = `username=${data.username}`;
document.cookie = `password=${data.password}`;
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
You just set data to cookie:
document.cookie =
of you can use some npm lib like this:
https://www.npmjs.com/package/react-cookie

Resources