Cannot access 'useState' before initialization in react.js - node.js

In react.js I am adding a form with some parameter.
import React , {useState} from "react";
AddUser component has some parameter in which I have to store data.
const AddUser = () => {
const [user, useState] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});
This code is used for initializing the parameter of useState.
const {name,username,email,phone,website} = user;
const onInputChange = e => {
console.log(e.target.value)
}
return (
<div className="container mt-5">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Add User</h2>
This is the form where I submit some data of parameters.
<form>
<div class="form-group mb-4">
<input type="text" value={name} name="name" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter Name" />
</div>
<div class="form-group mb-4">
<input type="text" value={username} name="username" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Username" />
</div>
<div class="form-group mb-4">
<input type="email" value={email} name="email" onChange={e => onInputChange(e)} class="form-control" aria-describedby="emailHelp" placeholder="Enter email" />
</div>
<div class="form-group mb-4">
<input type="text" value={phone} name="phone" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Contact" />
</div>
<div class="form-group mb-4">
<input type="text" value={website} name="website" onChange={e => onInputChange(e)} class="form-control" placeholder="Enter Website" />
</div>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
</div>
</div>
)
}
export default AddUser;
Error:
Uncaught ReferenceError: Cannot access 'useState' before initialization
at AddUser (AddUser.js:4:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
at performConcurrentWorkOnRoot (react-dom.development.js:25750:1)

useState is a react hook, you cannot use its name to name a variable or function. Change your AddUser code shown on this page to this:
const AddUser = () => {
const [user, setUser] = useState({
name: " ",
username: " ",
email: " ",
phone: " ",
website: " "
});

Related

How to integrate 2checkout with reactjs and nodejs?

I am trying to integrate 2checkout API in my reactjs &nodejs project.I reffered the documents which 2co provided.I created an account and in that webhooks&API i have "Merchant Code" and "Secret Key" but there is no "Publishable key" and "Private Key" Why?
what i have is:
render = () => {
return(
<form id="myCCForm" onSubmit={this.Submit}>
<input
id="token"
name="token"
type="hidden"
value=""
></input>
<div>
<label>
<span>Card Number</span>
</label>
<input
id="ccNo"
type="text"
size="20"
value=""
autocomplete="off"
required
/>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
</label>
<input
type="text"
size="2"
id="expMonth"
required
></input>
<span> / </span>
<input
type="text"
size="2"
id="expYear"
required
></input>
</div>
<div>
<label>
<span>CVC</span>
</label>
<input
id="cvv"
size="4"
type="text"
value=""
autocomplete="off"
required
></input>
</div>
<input type="submit" value="Submit Payment"></input>
</form>
)}
submit=()=>{
let args = {
sellerId: "",//gave merchant code here
publishableKey: "",//as there is no publishable key what will give here?
ccNo: "",
cvv: "",
expMonth: "",
expYear: ""
};
window.TCO.loadPubKey("sandbox", () => {
window.TCO.requestToken(args).then(data => {
console.log("data");
});
});
How can i resolve this problem?

Unable to send image along with my form details angular client is showing status code:422 with Unprocessable entry

I'm trying to send an image along with an enquiry form containing some details while sending it from angular to nodejs. It shows an error with status 422 & Unprocessable entry.
While sending it to the nodejs backend it shows Unprocessable entry. I couldn't find out an anwser for this error. Please help me out over this.
Html Component:
<h1 class="page-header">Student Enquiry Form</h1>
<!-- Custom Success/Error Message -->
<div class="row show-hide-message">
<div [ngClass]="messageClass">
{{ message }}
</div>
</div>
<div class="example-container">
<form class="example-container" [formGroup]="form
(ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput placeholder="Enter your email"
formControlName="email" >
<mat-error *ngIf="form.controls['email'].errors?.email &&
!form.controls['email'].errors?.required">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="form.controls['email'].errors?.required">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Enter your fullname"
formControlName="fullName" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Enter your fathername"
formControlName="fatherName" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Enter your mothername"
formControlName="motherName" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Enter your mobilenumber"
type="number" formControlName="mobilenumber" required>
</mat-form-field>
<label>Gender: </label>
<mat-radio-group formControlName="Gender">
<mat-radio-button value="male">Male</mat-radio-button>
<mat-radio-button value="female">Female</mat-radio-button>
<mat-radio-button value="others">Others</mat-radio-button>
</mat-radio-group>
<mat-form-field>
<textarea matInput placeholder="Textarea"></textarea>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Select">
<mat-option value="option">Option</mat-option>
<mat-option value="AI">AI</mat-option>
<mat-option value="IOT">IOT</mat-option>
<mat-option value="BlockChain">BlockChain</mat-option>
</mat-select>
</mat-form-field>
<div>
<div>
<input type="file" (change)="onFileChange($event)" />
</div>
<div class="example-button-row">
<button type="submit" mat-button color="warn">Register</button>
</div>
</div>
Component.ts file
onFileChange(event){
this.selectedFile = <File>event.target.files[0];
this.fd.append('file', this.selectedFile, this.selectedFile.name);
}
onSubmit(){
const student = {
email: this.form.get('email').value,
fullName: this.form.get('fullName').value,
motherName: this.form.get('motherName').value,
fatherName: this.form.get('fatherName').value,
mobilenumber: this.form.get('mobilenumber').value,
}
this.fd.append('student', JSON.stringify(student))
this.studentService.getDetails(this.fd).subscribe(data =>{
console.log(data)
this.studentDetails = data;
if (!this.studentDetails.success) {
this.messageClass = 'alert alert-danger'; // Set an error class
this.message = this.studentDetails.message; // Set an error message
} else {
this.messageClass = 'alert alert-success'; // Set a success class
this.message = this.studentDetails.message; // Set a success message
this.router.navigate(['/home']);
}
})
}
Service.ts
getDetails(formData){
let headers = new HttpHeaders()
return this.http.post(this.domain + 'authentication/register',
formData).map(res =>res)
}

image doesnt upload using multer

Ok so in my app I am trying to allow image uploading using multer. My app is built using node.js and my database is using mongodb. When I create an account and select an image for the avatar image, it creates the account but automatically uses the no-image.png file I have setup in case someone doesn't select an image. Here is the code... Any help will be awesome.
// handle signup logic
router.post("/register", function(req, res) {
upload(req, res, function(err) {
if(err){
req.flash("error", err.message);
return res.redirect("/register");
}
var newUser = new User({
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
bio: req.body.bio
});
if(typeof req.file !== "undefined") {
newUser.avatar = '/uploads/userImg/' + req.file.filename;
} else {
newUser.avatar = '/uploads/userImg/no-image.png';
}
console.log(newUser);
if(req.body.adminCode === process.env.ADMINCODE) {
newUser.isAdmin = true;
}
if(req.body.answer !== process.env.SECRET){
req.flash("error", "answer the question");
return res.redirect("back");
} else {
User.register(newUser, req.body.password, function(err, user){
if(err){
return res.render("register", {error: err.message});
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Welcome to Let's Camp " + user.username);
res.redirect("/campgrounds");
});
});
}
});
});
var multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/uploads/userImg');
},
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
var upload = multer({ storage : storage}).single('image');
<% include ./partials/header %>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<form action="/register" method="post">
<h1 class="text-center">Sign Up</h1>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-2">
<div class="form-group">
<label for="firstName">First Name</label>
<input id="firstName" class="form-control" type="text" name="firstName" placeholder="First Name*" required>
</div>
</div>
<div class="col-xs-4 col-xs-offset-0">
<div class="form-group">
<label for="lastName">Last Name</label>
<input id="lastName" class="form-control" type="text" name="lastName" placeholder="Last Name*" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-2">
<div class="form-group">
<label for="email">Email</label>
<input id="email" class="form-control" type="email" name="email" placeholder="Email*" required>
</div>
</div>
<div class="col-xs-4 col-xs-offset-0">
<div class="form-group">
<label for="avatar">Avatar Image URL</label>
<input id="avatar" class="form-control" type="file" name="avatar">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-2">
<div class="form-group">
<label for="username">Username</label>
<input id="username" class="form-control" type="text" name="username" placeholder="Username*" required>
</div>
</div>
<div class="col-xs-4 col-xs-offset-0">
<div class="form-group">
<label for="password">Password</label>
<input id="password" class="form-control" type="password" name="password" placeholder="Password*" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<div class="form-group">
<label for="bio">Bio</label>
<textarea id="bio" class="form-control" type="bio" name="bio" rows="5" placeholder="Write a short description of yourself and what you enjoy about camping."></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-2">
<div class="form-group">
<label for="adminCode">Admin Code</label>
<input id="adminCode" class="form-control" type="text" name="adminCode" placeholder="Admin Code">
</div>
</div>
<div class="col-xs-4 col-xs-offset-0">
<div class="form-group">
<label for="number">Enter: I Love Camping</label>
<input id="number" class="form-control" type="text" name="answer" placeholder="Answer*" required>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">Sign Up!</button>
</div>
Go Back
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<p class="text-center"><strong>*</strong> indicates a required field.</p>
</div>
</div>
</div>
<% include ./partials/footer %>
If I use enctype="multipart/form-data" I get an error for some reason but if I leave it off it completes but the image still doesnt upload. Just reverts to the no-image.png
If You want to post file You've to use entype="multipart/form-data":
<form action="/register" method="post" enctype="multipart/form-data">
If You've other problems so fix that problem.
from documentation :
.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.
So create upload method like this and call it in Your router:
var uploadAvatar = multer({ storage : storage}).single('avatar');
or rename Your input file name="image" :
<input id="avatar" class="form-control" type="file" name="image">

Cannot POST Form in Node

I am trying to post a simple form from a static page to a database and then re-render the page. Right now I am getting a "Cannot Post /Index" error.
Here is my the form code:
<div class="contact-form">
<form action="/index" method="post">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="col-md-6">
<input type="tel" class="form-control" placeholder="Phone Number" name="phone">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="# of Trucks" name="truckNum">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Company" name="company">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Address" name="address">
</div>
<div class="col-md-12">
<textarea class="form-control" placeholder="Message" rows="4" name="message"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" value="Send">
</div>
</form>
</div>
Here is the router code:
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
app.post("/", function(req,res){
db.Contact.create({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
company:req.body.company,
address:req.body.address,
truckNumber:req.body.truckNum
}).then(function(data) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
})
};
Change '/index' to '/' in<form action="/index" method="post">.

Forms not working (using Bootstrap,Node.js and mongoose)

I have this simple form code which works perfectly with the node.js and mongoose, it saves data and everything but as soon as I add my other bootstraps features it doesn't save any data into database any more. Here are the two codes:
The one which works perfectly:
<div class="row">
<div class="col-lg-12">
<div class="col-xs-8 col-sm-8 col-md-8">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<form method="POST" action="/samples">
<input type="text" name="fullName" id="fullName" class="input-lg " placeholder="your full name" data-required="true">
<input type="text" name="age" id="age" class="input-lg" placeholder="age">
<input type="text" name="city" id="city" class="input-lg" placeholder="Your City">
<input type="text" name="job" class="input-lg" placeholder="Your Job">
<input type="text" name="username" class="input-lg " placeholder="prefered username" data-required="true">
<input type="password" name="password" class="input-lg" placeholder="Password">
<input type="email" name="email" class="input-lg " placeholder="your email" data-required="true">
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is the one with that small addition which doesn't work:
<div class="slide story" id="slide-2" name="slide2" data-slide="2">
<div class="container">
<div class="row title-row">
<div class="col-12 font-title">"Start Exploring Here"</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-12">
<div class="col-xs-8 col-sm-8 col-md-8">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<form method="POST" action="/samples">
<input type="text" name="fullName" id="fullName" class="input-lg " placeholder="your full name" data-required="true">
<input type="text" name="age" id="age" class="input-lg" placeholder="age">
<input type="text" name="city" id="city" class="input-lg" placeholder="Your City">
<input type="text" name="job" class="input-lg" placeholder="Your Job">
<input type="text" name="username" class="input-lg " placeholder="prefered username" data-required="true">
<input type="password" name="password" class="input-lg" placeholder="Password">
<input type="email" name="email" class="input-lg " placeholder="your email" data-required="true">
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is the bit of code for node.js
mongoose.connect('mongodb://localhost/Try');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
var Schema = new mongoose.Schema({
fullName:String,
age: String,
city: String,
job: String,
username: String,
password: String,
_id: String
});
var user = mongoose.model('Users',Schema);
app.post('/samples', function(req,res){
new user({
_id:req.body.email,
fullName:req.body.fullName,
age:req.body.age,
city:req.body.city,
job:req.body.job,
username:req.body.username,
password:req.body.password,
}).save(function(err, doc){
if(err) res.json(err);
else res.render('samples');
});
});
});
I can't figure out why it doesn't work. I would really appreciate it if you let me know what is the problem with that small bit which mess the whole thing.
Thanks
The slider is likely preventing the default action of your form. Try adding an explicit click listener on your button with jQuery:
$('button').click( function() {
$('form').submit();
});

Resources