DB adding characters on Inputs - javascript

I have a form on the client side in which I send data (username and password) to my DB through a socket event:
CLIENT:
export default function RegisterForm() {
const [user, setUser] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
const handleSubmit = () => {
socket.emit("newuser", { user, password });
navigate("/");
};
return (
<>
<div className="join-container">
<header className="join-header">
<h1>
<i className="fas fa-smile"></i> Registration Page
</h1>
</header>
<main className="join-main">
<form action="chat.html">
<div className="form-control">
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
id="username"
value={user}
onChange={(e) => setUser(e.target.value)}
placeholder="Set username..."
required
/>
</div>
<div className="form-control">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="pasword"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Set new password..."
required
/>
</div>
</form>
<button type="submit" className="btn" onClick={handleSubmit}>
Submit
</button>
</main>
</div>
</>
);
}
SERVER:
socket.on("newuser", async (msg) => {
try {
Users.create({
username: msg.user,
password: msg.password,
});
} catch (err) {
console.log(err);
}
});
DB MODEL:
const Users = db.define("users", {
username: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
});
The problem is that when I submit the password, it stores blanck carachters.
For example If "1234" password is submited, on the DB I see "1234----------"
"-" are blank spaces
What could be the problem?

Related

Form not submitting properly using Reactjs

I am working with Reacjs/nextjs,Right now i am trying to submit "login form" i am getting alert but page is also reloading,I just want page should not reload,Where i am wrong ? Here is my current code in "index.tsx"
import React from 'react';
import axios from 'axios';
const LoginForm = () => {
const [formValue, setformValue] = React.useState({
email: '',
password: ''
});
const handleSubmit = (event) => {
alert("its workinggg");
// we will fill this in the coming paragraph
}
const handleChange = (event) => {
setformValue({
...formValue,
[event.target.name]: event.target.value
});
}
return (
<form onSubmit={handleSubmit}>
<p>Login Form</p>
<input
type="email"
name="email"
placeholder="enter an email"
value={formValue.email}
onChange={handleChange}
/>
<input
type="password"
name="password"
placeholder="enter a password"
value={formValue.password}
onChange={handleChange}
/>
<button
type="submit"
>
Login
</button>
</form>
)
};
export default LoginForm;
Use preventDefault method to prevent default reload.
It works with all events which have default action.
const LoginForm = () => {
const [formValue, setformValue] = React.useState({
email: '',
password: ''
});
const handleSubmit = (event) => {
event.preventDefault() // <----- HERE
alert("its workinggg");
// we will fill this in the coming paragraph
}
const handleChange = (event) => {
setformValue({
...formValue,
[event.target.name]: event.target.value
});
}
return (
<form onSubmit={handleSubmit}>
<p>Login Form</p>
<input
type="email"
name="email"
placeholder="enter an email"
value={formValue.email}
onChange={handleChange}
/>
<input
type="password"
name="password"
placeholder="enter a password"
value={formValue.password}
onChange={handleChange}
/>
<button
type="submit"
>
Login
</button>
</form>
)
};

How can I persist updated form data after submit?

So I have some formdata in my react app that I want to persist after I make a put request to the mongodb. Problem is that the change is not visible on page refresh. It is only after I log out and log in again that I can see the updated value in the form.
For example let's say that I want to change my first name from John to Eric. The change will update but not in the form. In the form the value will still be John until I log out and in again.
It feels almost like it has to do with the jwt token but I don't know. Any ideas what the problem can be?
export const Edit = () => {
const navigate = useNavigate();
const user = Cookies.get("access_token");
const [id, setId] = useState(null)
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")
const [city, setCity] = useState("")
const [email, setEmail] = useState("")
const checkUser = async () => {
try {
const res = await axios
.get(`${process.env.REACT_APP_API_URL}user/protected`, {
withCredentials: true,
headers: {
Authorization: `Bearer ${user}`,
},
})
console.log(res.data.user);
setId(res.data.user.id)
setFirstName(res.data.user.firstName)
setLastName(res.data.user.lastName)
setCity(res.data.user.city)
setEmail(res.data.user.email)
} catch (error) {
console.warn(error)
}
}
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, []);
const updateUser = async () => {
try {
const userData = {
firstName: firstName,
lastName: lastName,
city: city,
email: email
}
const API_URL = `${process.env.REACT_APP_API_URL}user/`;
const userId = id;
const res = await axios.put(API_URL + "/" + userId + "/edit", userData)
setFirstName(res.data.firstName)
setLastName(res.data.lastName)
setCity(res.data.city)
setEmail(res.data.email)
// works and is updated in the database
} catch (error) {
console.warn(error)
}
}
return (
<>
<section className="m-5">
<h1 className="mb-5 text-center">Settings</h1>
<form className="row g-3">
<div className="col-md-6">
<label htmlFor="firstName" className="form-label">
First name
</label>
<p>{formErrors.firstName}</p>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="lastName" className="form-label">
Last name
</label>
<p>{formErrors.lastName}</p>
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="city" className="form-label">
City
</label>
<p>{formErrors.city}</p>
<input
type="text"
className="form-control"
id="city"
name="city"
value={city}
onChange={(e) => setCity(e.target.value)}
/>
</div>
<div className="col-md-6">
<label htmlFor="email" className="form-label">
Email
</label>
<p>{formErrors.email}</p>
<input
type="email"
className="form-control"
id="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="col-12 pt-4 text-center">
<button
type="submit"
className="btn btn-primary btn-lg"
onClick={updateUser}
>
Update
</button>
</div>
<div className="col-12 pt-1 text-center">
<button
type="submit"
className="btn btn btn-lg"
>
<a href="edit/password" className="text-decoration-none">
Change Password
</a>
</button>
</div>
</form>
</section>
</>
);
};
Add user as a dependency to the useEffect's dependency array:
useEffect(() => {
if (!user) {
navigate('/')
} else {
checkUser();
}
}, [user]);

Not able to submit the data to firebase from contact form

import React, { useState } from 'react'
import styled from 'styled-components'
import Title from '../Components/Title'
import { InnerLayout, MainLayout } from '../Styles/Layout'
import Button from '../Components/Button'
import { db } from '../firebase';
function Contact() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [subject, setSubject] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
db.collection('mail').add({
name: name,
email: email,
subject: subject,
message: message,
})
.then(() => {
alert("Thank you for contacting. Your message has been sent successfully.");
})
.catch((err) => {
alert(err.message);
});
setName('')
setEmail('')
setSubject('')
setMessage('')
};
return (
<MainLayout>
<Title title={'Contact'} span={'Contact'} />
<ContactMain>
<InnerLayout className='contact-section'>
<div className="left-content">
<div className="contact-title">
<h4>Get In Touch</h4>
</div>
<form className="form" onSubmit={handleSubmit}>
<div className="form-field">
<label htmlFor="name">Enter Your Name</label>
<input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="email">Enter Your Email</label>
<input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="subject">Enter Your Subject</label>
<input type="text" id="subject" value={subject} onChange={(e) => setSubject(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="text-area">Enter Your Message</label>
<textarea name="textarea" id="textarea" cols="30" rows="10" value={message} onChange={(e) => setMessage(e.target.value)}></textarea>
</div>
<div className="form-field f-button">
<Button title="Send Email" />
</div>
</form>
</div>
</InnerLayout>
</ContactMain>
</MainLayout>
)
}
I don't know why but I am not able to send the details to my firebase database. I am not able to find the issue in this code. I have copied the firebase database key and all in the firebase.js and then imported it in this contact.js and I then made the necessary changes in this. Still, I am not able to figure out the issue.
I would reset the form once the promise returned by add() is resolved.
const handleSubmit = (e) => {
e.preventDefault();
db.collection('mail').add({
name: name,
email: email,
subject: subject,
message: message,
}).then(() => {
// Reset those states here
setName('')
setEmail('')
setSubject('')
setMessage('')
alert("Thank you for contacting. Your message has been sent successfully.");
}).catch((err) => {
alert(err.message);
});
};
I guess your states are being reset to "" before the document is added as those setState methods would have ran before the doc was added.
Potentially because your button html within its the button component type is not set to 'submit' - I had the same issue I think which ended up being super simple.

Problems with Registering User

So, I have a backend auth which is showing me the Userdata in the postman and as well in the Mongo. I had an error in the console xhr.js:177 POST http://localhost:3000/api/auth/register 404 (Not Found) which I think I fixed by adding ""http://localhost:5000/api/auth/register", instead of just api/auth/register in the post method, but now when I try to register I am getting this error Unhandled Rejection (TypeError): Cannot read property 'data' of undefined. If someone would tell me why is this showing, and how to I fix it, I would be grateful. Thanks
import axios from "axios";
import { Link } from "react-router-dom";
const Register = ({ history }) => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const registerHandler = async (e) => {
e.preventDefault();
const config = {
header: {
"Content-Type": "application/json",
},
};
if (password !== confirmpassword) {
setPassword("");
setConfirmPassword("");
setTimeout(() => {
setError("");
}, 5000);
return setError("Passwords do not match");
}
try {
const { data } = await axios.post(
"http://localhost:5000/api/auth/register",
{
username,
email,
password,
},
config
);
localStorage.setItem("authToken", data.token);
history.push("/");
} catch (error) {
setError(error.response.data.error);
setTimeout(() => {
setError("");
}, 5000);
}
};
return (
<div className="register-screen">
<form onSubmit={registerHandler} className="register-screen__form">
<h3 className="register-screen__title">Register</h3>
{error && <span className="error-message">{error}</span>}
<div className="form-group">
<label htmlFor="name">Username:</label>
<input
type="text"
required
id="name"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input
type="email"
required
id="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
required
id="password"
autoComplete="true"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="confirmpassword">Confirm Password:</label>
<input
type="password"
required
id="confirmpassword"
autoComplete="true"
placeholder="Confirm password"
value={confirmpassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Register
</button>
<span className="register-screen__subtext">
Already have an account? <Link to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
you need to check for error.response existence. Seems like it is undefined in your case.
if (error.response) {
setError(error.response.data.error);
}
setTimeout(() => {
setError("");
}, 5000);
That will help you with this error Cannot read property 'data' of undefined but to answer why you're getting xhr.js:177 POST http://localhost:3000/api/auth/register 404 (Not Found) we need more information. Simply there is no /api/auth/register handler on your server.

How to add select option data into the server using react js

I am currently working on an e-commerce project using react js. There is a problem of saving/adding user data especially gender( select option). Anyone help to solve this problem.
I use react-select as the component in user from as:
User_form:
This is our user form component that is used for creating users.
import React, { Component, Fragment } from "react";
import { Tabs, TabList, TabPanel, Tab } from "react-tabs";
import PropTypes from "prop-types";
import { register } from "../../redux/actions/auth";
import { createMessage } from "../../redux/actions/message";
import { connect } from "react-redux";
import Select from "react-select";
export class Tabset_user extends Component {
state = {
first_name: "",
last_name: "",
username: "",
email: "",
password: "",
password2: "",
gender: [],
};
static propTypes = {
register: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool,
};
onSubmit = (e) => {
e.preventDefault();
const {
first_name,
last_name,
username,
email,
password,
password2,
phone,
gender,
} = this.state;
if (password !== password2) {
// this.props.createMessage({ passwordNotMatch: "Passwords do not match" });
alert("Password don't match");
} else {
const newUser = {
first_name,
last_name,
username,
password,
email,
phone,
gender,
};
this.props.register(newUser);
}
};
onChange = (e) => this.setState({ [e.target.name]: e.target.value });
handleChange = (value) => {
this.setState({ gender: value });
};
render() {
const options = [
{ value: "Male", label: "Male" },
{ value: "Female", label: "Female" },
{ value: "Perfer Not To Say", label: "Perfer Not to Say" },
];
const {
first_name,
last_name,
username,
email,
password,
password2,
phone,
} = this.state;
return (
<Fragment>
<Tabs>
<TabList className="nav nav-tabs tab-coupon">
<Tab className="nav-link">Account</Tab>
<Tab className="nav-link">Permission</Tab>
</TabList>
<TabPanel>
<form
className="needs-validation user-add"
onSubmit={this.onSubmit}
>
<h4>Account Details</h4>
<div className="form-group row">
<label className="col-xl-3 col-md-4">First Name</label>
<input
className="form-control col-xl-8 col-md-7"
id="first_name"
type="text"
name="first_name"
value={first_name}
onChange={this.onChange}
placeholder="First Name"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">Last Name</label>
<input
className="form-control col-xl-8 col-md-7"
id="validationCustom1"
type="text"
name="last_name"
value={last_name}
onChange={this.onChange}
placeholder="Last Name"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">
<span>*</span> Email
</label>
<input
className="form-control col-xl-8 col-md-7"
id="email"
type="email"
name="email"
value={email}
onChange={this.onChange}
placeholder="Email Address"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">
<span>*</span> Username
</label>
<input
className="form-control col-xl-8 col-md-7"
id="username"
type="text"
name="username"
value={username}
onChange={this.onChange}
placeholder="Username"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">
<span>*</span> Password
</label>
<input
className="form-control col-xl-8 col-md-7"
id="validationCustom3"
type="password"
name="password"
value={password}
onChange={this.onChange}
placeholder="Password"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">
<span>*</span> Confirm Password
</label>
<input
className="form-control col-xl-8 col-md-7"
id="validationCustom4"
type="password"
name="password2"
value={password2}
onChange={this.onChange}
placeholder="Confirm Password"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">Gender</label>
<Select
className="form-control col-xl-8 col-md-7"
options={options}
value={this.state.gender}
onChange={this.handleChange}
name="gender"
/>
</div>
<div className="form-group row">
<label className="col-xl-3 col-md-4">Phone</label>
<input
className="form-control col-xl-8 col-md-7"
id="phone"
type="number"
name="phone"
value={phone}
onChange={this.onChange}
placeholder="Phone Number"
/>
</div>
<div className="pull-right">
<button type="submit" className="btn btn-primary">
Save
</button>
</div>
</form>
</TabPanel>
</Tabs>
</Fragment>
);
}
}
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps, { register, createMessage })(
Tabset_user
);
Action.js:
This is an action creator where I use Axios to call post requests to register the user.
import * as types from "../../constants/actionTypes";
import axiosInstance from "./axios";
// LOGIN USER
export const login = (username, password) => (dispatch) => {
const body = {
username: username,
password: password,
};
axiosInstance
.post("api/token/obtain/", body)
.then((res) => {
console.log(res);
axiosInstance.defaults.headers["Authorization"] =
"JWT " + res.data.access;
dispatch({
type: types.LOGIN_SUCCESS,
payload: res.data,
});
})
.catch((err) => {
console.log(err);
// dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: types.LOGIN_FAIL,
});
// alert("Invalid username and Password");
});
};
// REGISTER USER
export const register = ({
first_name,
last_name,
email,
username,
password,
phone,
gender,
}) => (dispatch) => {
// Request Body
// const body = {
// first_name: first_name,
// last_name: last_name,
// email: email,
// username: username,
// password: password,
// };
axiosInstance
.post("/api/user/create/", {
first_name,
last_name,
email,
username,
password,
phone,
gender,
})
.then((res) => {
console.log(res);
dispatch({
type: types.REGISTER_SUCCESS,
payload: res.data,
});
// history.push(`${process.env.PUBLIC_URL}/pages/create-page`);
})
.catch((err) => {
// dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: types.REGISTER_FAIL,
});
});
};
//LOGOUT USER
export const logout = () => (dispatch) => {
try {
const response = axiosInstance.post("api/blacklist/", {
refresh_token: localStorage.getItem("refresh"),
});
if (
response
.then((data) => {
if (data.statusText === "Reset Content") {
localStorage.removeItem("access");
localStorage.removeItem("refresh");
axiosInstance.defaults.headers["Authorization"] = null;
dispatch({
type: types.LOGOUT_SUCCESS,
});
}
})
.catch((err) => console.log(err))
);
} catch (e) {
console.log(e);
}
};

Categories

Resources