get elements from my fetch to render() using reactjs - javascript

i need to hide the authentication form when user is connected and show it when he click on logout button.
constructor (props) {
super(props);
this.state = {
cnx_mail: '',
cnx_pwd: '',
items: [],
errors: {},
formErrors: {cnx_mail: '', cnx_pwd: ''},
emailValid: false,
passwordValid: false,
formValid: false
}
this.handleUserInput = this.handleUserInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
The login button :
handleSubmit = (event) => {
event.preventDefault();
fetch(`${API}/api/connexion`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify ({
email: this.state.cnx_mail,
password: this.state.cnx_pwd,
})
})
.then(res => res.json())
.then(json => {
console.log(json);
//Here we get all the token
localStorage.setItem('head', json.result.split('.')[0]);
localStorage.setItem('payload', json.result.split('.')[1]);
localStorage.setItem('signature', json.result.split('.')[2]);
//Here we get the role to redirect user to accounts (if admin)
roole = JSON.parse(atob(json.result.split('.')[1])).account[0].role === 'admin';
this.setState({ therole : roole });
if(roole) {
console.log(json.result);
this.props.history.push('/accounts');
}
else {
console.log("is user");
}
return roole;
})
}
this code says that if it's a simple user (role == "admin") he will be redirected to accounts page, otherwse (role=="user") he will stay in the same page ("/") but i have to hide the authentication form which is normally logical.
This is the form :
<form className="demoForm" onSubmit={this.handleSubmit} noValidate encType="application/x-www-form-urlencoded">
<div className="alreadysubscribed-input">
<div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_mail)}`}>
<input type="email" required className="form-control fatb-input input-form" name="cnx_mail"
value={this.state.cnx_mail}
id="cnx_mail"
onChange={this.handleUserInput} error={errors.cnx_mail} />
<label className="fatb-label" htmlFor="cnx_mail">Email</label>
<div className="fatb-bar"></div>
</div>
<div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_pwd)}`}>
<input type="password" required className="form-control fatb-input input-form" name="cnx_pwd"
value={this.state.cnx_pwd}
id="cnx_pwd"
onChange={this.handleUserInput} error={errors.cnx_pwd} />
<label className="fatb-label" htmlFor="cnx_pwd">Mot de passe</label>
<div className="fatb-bar"></div>
</div>
</div>
<FormErrors formErrors={this.state.formErrors} />
<div className="btn-cnx">
{/* <span className="mas">Se connecter</span> */}
<button className="fatb-btn bubbly-button btn-anim3 w100p" type="submit" name="cnx_btn" disabled={!this.state.formValid}>se connecter</button>
</div>
</form>
Thank you

Related

Save data and image in table

I'm trying to save information in a table, which also has a field of type varbinary(max) (an image) (SQL Server)
class AddDoctor extends Component {
state = {
file: null,
name: "",
phoneNumber: "",
email: "",
status: "Active",
specialty: "",
specialities: [],
};
componentDidMount() {
const URL = "http://localhost:55317/api/TSpecialties";
ApiService.get(URL)
.then((data) => this.setState({ specialities: data }))
.catch((err) => console.log(err));
}
imgClick = () => {
const file = document.querySelector("#id-file");
file.click();
};
handleChange = (e) => {
const state = this.state;
state[e.target.name] = e.target.value;
this.setState({
...state,
});
};
handleFileChange = (event) => {
this.setState({
file: URL.createObjectURL(event.target.files[0]),
});
};
handleSubmit = (e) => {
e.preventDefault();
const URL = "http://localhost:55317/api/TDoctors/";
const DATA = {
doctorName: this.state.name,
doctorProfileImg: this.state.file,
doctorPhoneNumber: this.state.phoneNumber,
doctorEmail: this.state.email,
doctorStatus: this.state.status,
doctorSpecialtyId: Number(this.state.specialty),
};
let formData = new FormData();
formData.append("doctorProfileImg", DATA.doctorProfileImg);
formData.append("doctorName", DATA.doctorName);
formData.append("doctorEmail", DATA.doctorEmail);
formData.append("doctorPhoneNumber", DATA.doctorPhoneNumber);
formData.append("doctorStatus", DATA.doctorStatus);
formData.append("doctorSpecialtyId", DATA.doctorSpecialtyId);
const options = {
method: "POST",
body: formData
};
fetch(URL, options)
.then(res => console.log(res))
.catch(err => console.log("ERR: " + err))
};
render() {
return (
<div>
<form className="row g-3" onSubmit={this.handleSubmit}>
<div className="col-md-6">
<label htmlFor="name" className="form-label">
Name
</label>
<input
type="text"
className="form-control"
id="name"
name="name"
onChange={this.handleChange}
placeholder="Input your name"
/>
</div>
<div className="col-md-6">
<label htmlFor="email" className="form-label">
Email
</label>
<input
type="text"
onChange={this.handleChange}
name="email"
className="form-control"
id="email"
/>
</div>
<div className="col-md-6">
<label className="mb-2" htmlFor="phoneNumber">
Phone Number
</label>
<div className="input-group mb-2 mr-sm-2">
<div className="input-group-prepend">
<div className="input-group-text">+51</div>
</div>
<input
type="text"
onChange={this.handleChange}
className="form-control"
id="phoneNumber"
name="phoneNumber"
placeholder="Phone Number"
/>
</div>
</div>
<div className="col-md-12">
<label htmlFor="specialty" className="form-label">
Specialty
</label>
{/* */}
<select
id="specialty"
name="specialty"
onChange={this.handleChange}
className="form-select"
>
<option defaultValue>Choose...</option>
{this.state.specialities.map((sp) => (
<option value={sp.specialtyId}>
{sp.specialtyName}
</option>
))}
</select>
{/* */}
</div>
<div className="col-12 my-5">
<button
type="submit"
className="btn btn-outline-success w-100"
>
Save
</button>
</div>
</form>
<div className="col mx-5" style={{ minWidth: "250px" }}>
<img
src={ this.state.file}
id="img-select"
onClick={this.imgClick}
className="img-fluid img-thumbnail"
alt="doctor-img"
/>
<input
type="file"
style={{ display: "none" }}
onChange={this.handleFileChange}
id="id-file"
/>
</div>
</div>
);
}
}
Controller POST:
// POST: api/TDoctors
[HttpPost]
public async Task<IActionResult> PostTDoctor([FromBody] TDoctor tDoctor)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TDoctor.Add(tDoctor);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTDoctor", new { id = tDoctor.DoctorId }, tDoctor);
}
response on console developer tools when submit form:
and...
I have searched a lot of information and I cannot find the solution. I tried placing the multipart/form-data and it doesn't work either. I hope you can help me please.
Saving binary data to a SQL table is not a good practice, please use Azure Blob storage or some other storage service to store the files and just save the path of the file in the database column of a table

Why do I get a question mark in my localhost link? https://localhost:3000/?

I am using React to build a web app. And when I click the login button and make a http request, my localhost link will add "?" in the end.
My server works fine on the postman app, but would actually give a 204 as a response to my login request. So my login wouldn't work at the moment.
Below is my code for "Login.js"
My apologies for any confusion I've made.
Thank you for your help in advance.
enter code here
import React from "react";
import { Link, withRouter } from "react-router-dom";
import "./Login.css";
import axios from "axios";
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errorMessage: "",
isLoggedin: false,
};
this.handleInputValue = this.handleInputValue.bind(this);
// this.handleLogin = this.handleLogin.bind(this);
}
handleInputValue = (key) => (e) => {
this.setState({ [key]: e.target.value });
}
handleLogin = () => {
const { email, password } = this.state;
// if (!this.state.email || !this.state.password) {
// this.setState({ errorMessage: "Please check your email and password again." });
// } else {
axios.post("https://server.slowtv24.com/login",
{ email: email, password: password },
{ withCredentials: true }
)
.then((res) => {
console.log("login post res>>>", res);
// this.setState({
// isLoggedin: true,
// })
})
// }
}
render() {
return (
<div>
<div className="login">
<div className="login-half left">
<form>
<input type="text" placeholder="Enter email address" onChange={this.handleInputValue("email")} />
<input type="password" placeholder="Enter password" onChange={this.handleInputValue("password")} />
<button onClick={this.handleLogin}>Login</button>
</form>
</div>
<div className="bar bar-top"></div>
<span className="login-or">OR</span>
<div className="bar bar-bottom"></div>
<div className="login-half right">
<button>Login with GitHub</button>
<button>Login with Gmail</button>
</div>
</div>
</div>
)
};
}
export default Login;
You don't need form tag for login form, because you are handling the submit action in onClick event.
render() {
return (
<div>
<div className="login">
<div className="login-half left">
<input type="text" placeholder="Enter email address" onChange={this.handleInputValue("email")} />
<input type="password" placeholder="Enter password" onChange={this.handleInputValue("password")} />
<button onClick={this.handleLogin}>Login</button>
</div>
<div className="bar bar-top"></div>
<span className="login-or">OR</span>
<div className="bar bar-bottom"></div>
<div className="login-half right">
<button>Login with GitHub</button>
<button>Login with Gmail</button>
</div>
</div>
</div>
)
};
Regarding the question mark, you can add type="button" to your button.
Check this for more information.

Cannot Submit All Data in Form React

I am working on a very basic form in React, and I am having difficulty getting the data to submit properly. In this current setup, only the 'content' field is submitting correctly, eventhough the firstName, lastName, and email are all written the same. The radio buttons and dropdown are also not submitting. Any ideas?
import React from "react";
import axios from "axios";
import '../ticket.min.css'
class Ticket extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
content: ''
}
this.ticketName = React.createRef();
this.state = { tickets: [] };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onValueChange = this.onValueChange.bind(this);
}
handleChange = event => {
this.setState({ value: event.target.value });
}
handleSubmit = event => {
alert('Your ticket has been submitted');
event.preventDefault();
}
onValueChange = event => {
this.setState({
selectedOption: event.target.value
});
}
addTicket = () => {
let url = "http://localhost:8080/tickets";
axios.post(url, { firstName: this.ticketName.current.value, lastName: this.ticketName.current.value, email: this.ticketName.current.value, content: this.ticketName.current.value }).then(response => {
this.ticketName.current.value = "";
alert('Your ticket has been submitted');
});
};
getData = () => {
let url = "http://localhost:8080/tickets";
axios.get(url).then(response => this.setState({ tickets: response.data }));
};
render() {
return (
<div>
<form>
<label>First Name:</label>
<input ref={this.ticketName} type="text" name="firstName"/><br></br>
<label>Last Name:</label>
<input ref={this.ticketName} type="text" name="lastName"/><br></br>
<label>Email:</label>
<input ref={this.ticketName} type="text" name="email"/><br></br>
</form>
<form onSubmit={this.handleSubmit}>
<label>
Select a Category:<br></br>
<select value={this.state.value} onChange={this.handleChange}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</select>
</label>
</form>
<form>
<label>Please Describe Your Issue:</label><br></br>
<textarea name="content" ref={this.ticketName}/>
</form>
<form onSubmit={this.handleSubmit}>
<label>
Select the Urgency Level:<br></br>
<input type="radio" value="Urgent" checked={this.state.selectedOption === "Urgent"} onChange={this.onValueChange} />Urgent<br></br>
<input type="radio" value="Normal" checked={this.state.selectedOption === "Normal"} onChange={this.onValueChange} />Normal<br></br>
<input type="radio" value="Low Priority" checked={this.state.selectedOption === "Low Priority"} onChange={this.onValueChange} />Low Priority
</label>
</form>
<form>
<button type="button" className="btn btn-primary" onClick={this.addTicket}>Submit</button>
</form>
<h3>Pending Tickets</h3>
<button type="button" className="btn btn-primary" onClick={this.getData}>Show Pending</button>
<ul>
{this.state.tickets.map(p => (
<li key={p.id}>
{p.firstName}{p.lastName}
{/* {p.firstName} : { p.complete ? "complete" : "not complete" } <button type="button" className="btn btn-success">Complete</button><button type="button" className="btn btn-danger">Delete</button> */}
</li>
))}
</ul>
</div>
);
}
}
export default Ticket;
You should put fields in one form element and set the button type to submit.

Following a tutorial but onSumbit(e) not printing to console

I am following along with this tutorial (https://medium.com/#beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1) and am trying to print to console through the onSubmit function but this is not occurring and I do not know why. I've made sure to use the bind method, and everything seems to be referenced correctly. What am I missing here?
import React, {Component} from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
export default class CreateWorkout extends Component {
constructor(props) {
super(props); // Refers to the parent class constructorq
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeDescription = this.onChangeDescription.bind(this);
this.onChangeReps = this.onChangeReps.bind(this);
this.onChangeDuration = this.onChangeDuration.bind(this);
this.onChangeDate = this.onChangeDate.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username:'',
description: '',
reps: 0,
duration: 0,
date: new Date(),
users: []
}
}
componentDidMount() { // Invoked immediately after a component is mounted
this.setState({
users: ['test user'],
username: 'test user'
});
}
onChangeUsername(e) {
this.setState({
username: e.target.value
});
}
onChangeDescription(e) {
this.setState({
description: e.target.value
});
}
onChangeReps(e) {
this.setState({
reps: e.target.value
});
}
onChangeDuration(e) {
this.setState({
duration: e.target.value
});
}
onChangeDate(date) { // Need to add a date picker library for this
this.setState({
date: date
});
}
// Submit method for submitting an event of the form...
onSubmit(e) {
e.preventDefault();
const workout = {
username: this.state.username,
description: this.state.description,
reps: this.state.reps,
duration: this.state.duration,
date: this.state.date,
};
console.log(workout);
window.location = '/'; // After form is submitted, the location is updated so the user is taken back to the home page
}
render() {
return (
<div>
<h3>Create New Workout Log</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<select ref="userInput" required className="form-control" value={this.state.username} onChange={this.onChangeUsername}>
{
this.state.users.map(function(user) {
return <option key={user} value={user}>{user}</option>;
})
}
</select>
</div>
<div className="form-group">
<label>Description: </label>
<input type="text" required className="form-control" value={this.state.description} onChange={this.onChangeDescription}/>
</div>
<div className="form-group">
<label>Reps: </label>
<input type="text" className="form-control" value={this.state.reps} onChange={this.onChangeReps}/>
</div>
<div className="form-group">
<label>Duration: </label>
<input type="text" className="form-control" value={this.state.duration} onChange={this.onChangeDuration}/>
</div>
<div className="form-group">
<label>Date: </label>
<div><DatePicker selected={this.state.date} onChange={this.state.onChangeDate}/></div>
</div>
<div className="form-group">
<input type="submit" value="Create Workout Log" className="btn btn-primary"/>
</div>
</form>
</div>
);
}
}

how to send input data taken dynamically to the server using POST request

import React, { Component } from 'react';
import { Link } from 'react-router'
class Modals extends Component {
constructor(props){
super(props);
this.state = {inputuuid: '',
inputmajor: '' ,
inputminor: '' ,
inputmanufacturer: ''};
this.handleUuid = this.handleUuid.bind(this);
this.handleMajor = this.handleMajor.bind(this);
this.handleMinor = this.handleMinor.bind(this);
this.handleManufacturer = this.handleManufacturer.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
alert("started");
fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/beacons" ,
{
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGMyOTdiOWQzZWM4NjY4MDMwNDBlNjgiLCJlbWFpbCI6ImtrQGxpdGlmZXIuY29tIiwiZmlyc3ROYW1lIjoiS2lzaGxheSIsImxhc3ROYW1lIjoiS2lzaG9yZSIsImlhdCI6MTQ4OTE0NzgzM30.nHW5w3SSov8ySziblmw2VNlGI3CsZFR-v41Jeg9uBVs'
},
body: JSON.stringify({
name: "beacon name 1234",
description: "beacon description here for beacon",
uuid: "this.state.inputuuid1",
major: "this.state.inputmajor",
minor: "this.state.inputminor",
manufacturer: "this.state.inputmanufacturer",
beaconType: "type9",
location: "main gate8",
floor: "ist",
zone: "58c29c06d3ec866803040e6e"
})
}).then(function(response){
if(response.ok) {
console.log(response)
return response;
}
throw new Error('Network response was not ok.');
}).then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error);
});
}
handleUuid(event) {
this.setState({inputuuid: event.target.value});
}
handleMajor(event){
this.setState({inputmajor: event.target.value});
}
handleMinor(event){
this.setState({inputminor: event.target.value});
}
handleManufacturer(event){
this.setState({inputmanufacturer: event.target.value});
}
handleSubmit(event) {
alert('Submitted: ' + this.state.inputuuid + this.state.inputmajor + this.state.inputminor + this.state.inputmanufacturer);
event.preventDefault();
}
render() {
return (<div><div>
<div className="animated fadeIn">
<br /><div className="card" style={{ width: 57 + '%' }}>
<div className="card-header">
Beacon Settings
</div>
<div className="card-block">
<div className="input-group mb-1">
<span className="input-group-addon"><i className="icon-user"></i></span>
<input type="text" className="form-control" value={this.state.inputuuid} onChange={this.handleUuid} placeholder="UUID" />
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputmajor} onChange={this.handleMajor} placeholder="Major Number"/>
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputminor} onChange={this.handleMinor} placeholder="Minor Number"/>
</div>
<div className="input-group mb-1">
<span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
<input type="text" className="form-control" value={this.state.inputmanufacturer} onChange={this.handleManufacturer} placeholder="Manufacturer Number"/>
</div><center>
<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" onClick={this.handleSubmit} activeClassName="active">Save</Link>
<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" activeClassName="active">Advance Settings</Link>
</center>
</div>
</div>
</div></div>
</div>
)
}
}
export default Modals;
i had taken the user inputs now i want to send them to the server using POST request which i can not able to send.
i am only getting the values by the user and those can be seen by the alert i had put in that but can't able to send to the server
Try using following way
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
});
React require stringify post body data
You can create your inputField like this:
<input className="form-control" type="text" value={this.state.userData.firstName} required placeholder="First Name" onChange={this.handleChange.bind(this, 'firstName')} />
In your form component, you can define userData state object in this way:
this.state = {
userData: {
firstName: null,
lastName: null,
...
}
}
And for handleChange(), we can make it to accept dynamic keys for state variables:
handleChange(key, e, value){
let data = this.state.userData;
userData[key] = e.target.value;
this.setState({
userData: data
});
}
All you need to post then is this.state.userData.

Categories