Reactjs Usestate hook not sending data properlty to database - javascript

i know this is very easy question , but i am new with MERN technology. i am sending my data using React frontend to json-server npm module , all the codes works properly even though the data stored to backend smoothly . but the problem is that frontend data send extra fields to backend server which i don't want . you can see image there are 3 object 1st two object i have stored manually and third one i stored using React frontend application . the third one json-object stored extra fields are highlited here which i dont want . i am upload my working code please guide me .
//RegisterUser react Component :
import React from 'react'
import { useState } from 'react';
import loginImage from '../images/login2.jpeg';
import { NavLink } from 'react-router-dom';
import { addUser} from '../Service/api';
const initialValues = {
name:"",
username:"",
email:"",
phone:"",
}
const RegisterUser = () => {
const [user , setUser]= useState([initialValues]);
const { name,username, email, phone,} = user;
const style = {
color: 'black',
textAlign:'center'
};
const onValueChange= (e)=>{
console.log(e.target.Object);
setUser({...user, [e.target.name]:e.target.value})
console.log(user)
}
const addUserDetails= async()=>{
await addUser(user);
}
return (
<div>
<div>
<div className="container login-container">
<div className="row login-form-1">
<div className="col-md-6 ">
<h3 style={style}>Registration</h3>
<form>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="name" value={name} placeholder="Your Name *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="username" value={username} placeholder="username *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="email" value={email} placeholder="Your Email *" />
</div>
<div className="form-group">
<input type="text" className="form-control" onChange={(e)=> onValueChange(e)} name="phone" value={phone} placeholder="Mobile Number *" />
</div>
<div className="form-group">
<input type="submit" className="btnSubmit" onClick={()=> addUserDetails()} defaultValue="Login" />
</div>
</form>
</div>
<div className="col">
<img className="loginpic" src={loginImage} alt="login Image"/>
<div className="col">
<NavLink to="/login" className="signupIs" >I have already account</NavLink>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default RegisterUser
Api file
import axios from 'axios';
const url = 'http://127.0.0.1:3003/users';
export const getUsers = async ()=>{
return await axios.get(url);
}
export const addUser = async(user)=>{
return await axios.post(url,user);
}
again i am informing that the code is running no error while executing , but the issue is getting extra data field from React Frontend

When you first initialize your "user", you create it as an array:
const [user , setUser]= useState([initialValues]);
// ^---- here ---^
Then later you interpret the array as an object and add properties to it:
setUser({...user, [e.target.name]:e.target.value})
When doing so, that initial "user" would be a property called "0" since it's the first element of the array. So those "extra properties" are simply the initial state.
It sounds like what you intended was not to use an array at all:
const [user, setUser] = useState(initialValues);

Related

email_js__WEBPACK_IMPORTED_MODULE_2___default(...).sendForm is not a function

While I was use the Emailjs to use the email service on my portfolio website.
When i try to submit the form I get this above error..
This was the code that I used to create form, using reactjs..
If someone says about the dependencies then do refer the bellow image
the email-js dependency that was downloaded
import React from "react";
import "./contact.css";
import { useRef } from "react";
import emailjs from "email-js";
const Contact = () => {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
"service_6kimd8c",
"template_ql7mhzc",
form.current,
"vbCjePCf6E12Qm3kB"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
e.target.reset();
};
return (
<section className="contact" id="contact">
<h1 className="sub_heading">
Contact me <span></span>
</h1>
<form className="form" onSubmit={sendEmail} ref={form}>
<div className="field">
<input
type="email"
name="email"
id="email"
placeholder="email"
required
/>
<label htmlFor="email">Email</label>
</div>
<div className="field">
<input
type="text"
name="name"
id="name"
placeholder="name"
required
/>
<label htmlFor="name">Name</label>
</div>
<div className="field">
<textarea
name="message"
id=""
cols="30"
rows="10"
required></textarea>
</div>
<input type="submit" className="btn" value="Submit" />
</form>
</section>
);
};
export default Contact;
It looks like you are not using the suggested react package as per the official documentation. I suggest you remove the one you are using and install the described one #emailjs/browser and do:
import emailjs from '#emailjs/browser';
instead of your approach
import emailjs from "email-js";

Can't convert input element to re-usable component in react js

I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.
import React from "react";
const Input = ({ name, label, value, onChange }) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
value={value}
onChange={onChange}
id={name}
name={name}
type="text"
className="form-control"
/>
</div>
);
};
export default Input;
and imported it to my loginForm.jsx. Here is my loginForm.jsx render method
handleChange = ({ currentTarget: input }) => {
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account });
};
render() {
const { account } = this.state;
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
<Input
name="password"
value={account.password}
label="Password"
onChange={this.handleChange}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
But after adding below code to my loginForm.jsx,
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
code and deleted previous code ,
<div className="form-group">
<label htmlFor="username">Username</label>
<input
value={account.username}
name="username"
onChange={this.handleChange}
ref={this.username}
id="username"
type="text"
className="form-control"
/>
</div>
suddenly my login page not loading.(Empty page).
My login page's console showing below error.
The above error occurred in the <LoginForm> component:
at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

setting the value of more than one input

I am trying to build a login form. I am trying to set up the value of the email & password field individually. But as soon as I try to enter the text in the email text field, the same appears in the password field too. Can I have a solution to this?
Below is the code.
I guess the error is in OnChange fn where I am assigning the same value e.target.value to both the {email, passwaord}.
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
const LoginPage = () => {
let navigate = useNavigate();
const [credentials, setCredentials] = useState({email:"",password:""});
const onChange = (e) => {
setCredentials({email: e.target.value ,password: e.target.value})
console.log(credentials.email, credentials.password)
}
const goToSignUp = () => {
navigate("/signup");
}
return (
<>
<div className="container my-5">
<div id="loginbody">
<div className="mt-3">
<h2 className="my-3 display-3">Login Here</h2>
<form className="login-form p-5">
<div className="mb-3">
<label for="exampleInputEmail1" className="form-label">
Email address
</label>
<input
type="email"
className="form-control"
id="email"
name="email"
value={credentials.email}
aria-describedby="emailHelp"
onChange={onChange}
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label for="exampleInputPassword1" className="form-label">
Password
</label>
<input
type="password"
className="form-control"
id="password"
name="password"
value={credentials.password}
onChange={onChange}
/>
</div>
<div className="d-grid gap-2 my-4 col-6 mx-auto">
<button type="submit" className="btn btn-success">
Submit
</button>
</div>
<hr />
<div className="mb-3 text-center">
<div id="emailHelp" className="form-text center my-3">
Didn't have an account ?
</div>
<div className="d-grid gap-2 my-3 col-6 mx-auto">
<button onClick={goToSignUp} className="btn btn-success ">
SignUp Here !
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</>
);
};
export default LoginPage;
You have identified the problem. You need to pass the key to change as well.
Here passing a callback to setState which provides the current state as a parameter, cloning the state object using spread syntax, and then updating the relevant property in the copied object using the passed key as a computed property name.
const LoginPage = () => {
const [credentials, setCredentials] = useState({email:"",password:""});
const onChange = (e, key) => {
setCredentials(prevCredentials => ({...prevCredentials, [key]: e.target.value}))
}
return (
<>
//...
<input
type="email"
className="form-control"
id="email"
name="email"
value={credentials.email}
aria-describedby="emailHelp"
onChange={(e) => onChange(e, 'email')}
/>
//...
<input
type="password"
className="form-control"
id="password"
name="password"
value={credentials.password}
onChange={(e) => onChange(e, 'password')}
/>
//...
</>
);
};
Note: Calling console.log() right after setting state will not log the updated state, the new state values won't be available until the next render cycle. see: useState set method not reflecting change immediately
Use the proper key to the respective fields
const onChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value})
console.log(credentials);
}

Can't update state using useState

I'm trying to update the state of my component with useState in a register functional component。
when user input an invalid email address and click the submit button,
the following piece of code will return an error message
let response= await axios.post("/api/user/register",new_user,config);
I want to set error message into formData with this piece of code .
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
but the value of errors is empty,like this
What should I do to set error message into formData?
Here is my code:
import React ,{useState}from 'react'
import axios from "axios"
function Register() {
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
const {name,email,password,password2}=formData;
const setValue= e =>setFormData({...formData,[e.target.name]:e.target.value})
const submitData=async (e) =>{
e.preventDefault();
if(password!==password2){
console.log("passwords do not match ");
}else{
let new_user={name,email,password,}
try{
let config={
header:{
'Content-Type':'applicaiton/json'
}
}
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
}catch(error){
console.error(error);
}
}
}
return (
<div>
<section className="container">
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" onSubmit={e=>submitData(e)}>
<div className="form-group">
<input
type="text"
placeholder="Name"
name="name"
value={name}
onChange={e=>setValue(e)}
required />
</div>
<div className="form-group">
<input
type="email"
placeholder="Email Address"
onChange={e=>setValue(e)}
value={email}
name="email" />
<small className="form-text">This site uses Gravatar so if you want a profile image, use aGravatar email</small>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
onChange={e=>setValue(e)}
value={password}
name="password"
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
onChange={e=>setValue(e)}
value={password2}
name="password2"
minLength="6"
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? Sign In
</p>
</section>
</div>
)
}
export default Register
I think what you are doing wrong is that you are saving and object inside another object
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
formData is an object while errors is also an object.To go for a better approach make a seperate state for errors and append all the errors coming through those messages in an error object.
If you write a message in errors object where it is defined it will give you error
errors:{"hi","bye"}
There is no issue in your code. What you are trying to do is console the state as soon as you are setting it up.
setState is asynchronous which means you can’t call it on one line and assume the state has changed on the next.
If you check React docs
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
I'd suggest you use useEffect and then check for change in data of your state.
useEffect(() => {
console.log(formData)
}, [formData])

How to use ReactJS in Laravel

I am new to ReactJS and I am looking for a way to integrate it in Laravel. Is there any way that I can use React components within laravel views or it should be done only by using API as separate projects.
Use Laravel to provide the base view, but then after that all the views would be handled by React.Then Use Laravel as API and React as front-end. Also have a look at this blog
have a page as a root for react and do not forget to add every react page in web.php
Route::view('/courselist', 'app');
all your folders inside src should be copied into resources/js/react. then implement this in webpack.mix.js:
.js('resources/js/react', 'public/js/reactJs').react()
https://stackoverflow.com/a/66545875/13266927
To can use React Js with Laravel By creating Api's in laravel and later on integrating those APIs in react js project using Axios() or fetch() in react js. Steps to do it as follows:
Create Database in MySQL Database let's say using the name as "employees"
Install laravel, Create a new project in laravel and create a controller using the command
php artisan make:controller EmployeeController
Create Route in routes folder and inside it in api.php import controller using
use App\Http\Controllers\EmployeeController;
and then Create a route using:
Route::post('/employee',[EmployeeController::class,'employee']);
Create a function in EmployeeController named employee
and controller will be look like this as below:
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
class EmployeeController extends Controller
{
function employee(Request $req){
$employee = new Employee;
$employee -> TName=$req->input("TName");
$employee -> TID=$req->input("TID");
$employee -> Cnic=$req->input("Cnic");
$employee -> Email=$req->input("Email");
$employee -> Designation=$req->input("Designation");
$employee -> DId=$req->input("DId");
$employee -> Gender=$req->input("Gender");
$employee -> Address=$req->input("Address");
$employee -> PhNumber=$req->input("PhNumber");
$employee -> Skill=$req->input("Skill");
$employee->save();
return $employee;
}
}
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
public $timestamps=false;
}
After this test API http://127.0.0.1:8000/api/employee which was declared in api.php /employee in postman tool then later us this in react js project as below:
// import { useNavigate } from "react-router-dom";
// import { useState, useEffect } from "react";
import { useState } from "react";
import "./assignsubjectteacher.css";
// import Header from "./Header.js";
function Assignsubjectteacher() {
const [TName, setTName] = useState("");
const [TID, setTID] = useState("");
const [Cnic, setCnic] = useState("");
const [Email, setEmail] = useState("");
const [Designation, setDesignation] = useState("");
const [DId, setDId] = useState("");
const [Gender, setGender] = useState("");
const [Address, setAddress] = useState("");
const [PhNumber, setPhNumber] = useState("");
// const [IsHOD, setIsHOD] = useState("");
const [Skill, setSkill] = useState("");
async function assignsubjectteacher() {
// console.warn(name, department);
let item = {
TName,
TID,
Cnic,
Email,
Designation,
DId,
Gender,
Address,
PhNumber,
// IsHOD,
Skill,
};
// console.log(item);
let result = await fetch("http://127.0.0.1:8000/api/employee", {
method: "POST",
body: JSON.stringify(item),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
result = await result.json();
localStorage.setItem("user-info", JSON.stringify(result));
console.warn(result);
}
return (
<>
<div className="col-sm-8 offset-sm-3">
<div className="mt-10 col-sm-9 center">
<br />
<br />
<h2>Add Faculty</h2>
<input
type="text"
placeholder="Teacher's Name"
className="col-sm-12 form-control"
onChange={(e) => setTName(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="Teacher's ID"
className="col-sm-4 form-control"
onChange={(e) => setTID(e.target.value)}
/>
<input
type="text"
placeholder="Enter CNIC"
className="col-sm-4 form-control"
onChange={(e) => setCnic(e.target.value)}
/>
<input
type="email"
placeholder="Enter Email"
className="col-sm-4 form-control"
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<br />
<input
type="text"
placeholder="Enter Designation"
className="col-sm-4 form-control"
onChange={(e) => setDesignation(e.target.value)}
/>
<input
type="text"
placeholder="Enter DId"
className="col-sm-4 form-control"
onChange={(e) => setDId(e.target.value)}
/>
<select
placeholder="Select Gender"
className="col-sm-4 form-control"
onChange={(e) => setGender(e.target.value)}
>
<option>Select Gender</option>
<option>Male</option>
<option>Female</option>
</select>
<br />
<input
type="text"
placeholder="Address"
className="form-control"
onChange={(e) => setAddress(e.target.value)}
/>
<br />
<br />
<input
type="tel"
placeholder="Phone"
className="col-sm-6 form-control"
onChange={(e) => setPhNumber(e.target.value)}
pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}"
/>
<input
type="text"
placeholder="Enter Skill"
className="col-sm-6 form-control"
onChange={(e) => setSkill(e.target.value)}
/>
<br />
<br />
{/* <label for="IsHOD">IsHOD</label> */}
{/* <input
id="IsHOD"
type="checkbox"
onChange={(e) => setIsHOD(e.target.value)}
/> */}
<br />
<br />
<button onClick={assignsubjectteacher} className="btn btn-danger">
Add
</button>
</div>
</div>
</>
);
}
export default Assignsubjectteacher;

Categories

Resources