this.state not populating fields in editProfile.component - reactjs

Newbie here. Basic question I know. I have made a 'newProfile' component using pretty much the same mechanics as this and it's working! Now I need an editProfile component that updates the Profile form with props from the database using params.id. The URL shows the .id piece is working when I click 'edit' on a profile in a profileList component that is also working. This code is not getting errors, but it is not showing state for each of the fields.
What am I missing?
`
export default class EditProfile extends Component {
constructor(props) {
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeFirst = this.onChangeFirst.bind(this);
this.onChangeLast = this.onChangeLast.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onChangeDob = this.onChangeDob.bind(this);
this.onChangeLocation = this.onChangeLocation.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username: '',
first: '',
last: '',
email: '',
password:'',
dob:'',
location:'',
}
}
componentDidMount() {
axios.get('http://localhost:5000/profiles/'+this.props.match.params.id)
.then(response => {
this.setState({
username: response.data.username,
first: response.data.first,
last: response.data.last,
email: response.data.email,
password: response.data.password,
dob: response.data.dob,
location: response.data.location
})
})
.catch(function (error) {
console.log(error);
})
}
componentDidMount() {
axios.get('http://localhost:5000/users/')
.then(response => {
if (response.data.length > 0) {
this.setState({
users: response.data.map(user => user.username),
})
}
})
.catch((error) => {
console.log(error);
})
}
onChangeProfilePic(e) {
this.setState({
profilePic: e.target.value
});
}
onChangeUsername(e) {
this.setState({
username: e.target.value
});
}
onChangeFirst(e) {
this.setState({
first: e.target.value
});
}
onChangeLast(e) {
this.setState({
last: e.target.value
});
}
onChangeEmail(e) {
this.setState({
email: e.target.value
});
}
onChangePassword(e) {
this.setState({
password: e.target.value
});
}
onChangeDob(e) {
this.setState({
dob: e.target.value
});
} onChangeLocation(e) {
this.setState({
location: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const profile = {
username: this.state.username,
first: this.state.first,
last: this.state.last,
email: this.state.email,
password: this.state.password,
dob: this.state.dob,
location: this.state.location,
}
console.log(profile);
axios.post('http://localhost:5000/profiles/update'+this.props.match.params.id, profile)
.then(res => console.log(res.data));
window.location = '/';
}
render() {
return (
<div>
<h3>Edit Profile
</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username:
</label>
<input
type="text"
className="form-control"
value={this.state.username}
onChange={this.onChangeUsername}
/>
</div>
<div className="form-group">
<label>First Name:
</label>
<input
type="text"
className="form-control"
value={this.state.first}
onChange={this.onChangeFirst}
/>
</div>
<div className="form-group">
<label>Last Name:
</label>
<input
type="text"
className="form-control"
value={this.state.last}
onChange={this.onChangeLast}
/>
</div>
<div className="form-group">
<label>Email:
</label>
<input
type="text"
className="form-control"
value={this.state.email}
onChange={this.onChangeEmail}
/>
</div>
<div className="form-group">
<label>Password:
</label>
<input
type="text"
className="form-control"
value={this.state.password}
onChange={this.onChangePassword}
/>
</div>
<div className="form-group">
<input type="submit" value="Save" className="btn btn-primary" />
</div>
</form>
</div>
)}
}
`
Here is the error I'm getting in the console.
react-dom.development.js:86 Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
at input
at div
at form
at div
at CreateProfile (http://localhost:3000/static/js/bundle.js:194:5)
at RenderedRoute (http://localhost:3000/static/js/bundle.js:44214:5)
at Routes (http://localhost:3000/static/js/bundle.js:44678:5)
at div
at Router (http://localhost:3000/static/js/bundle.js:44609:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:42779:5)
at App

Related

Sending email using react and nodemailer

Been trying to make a contact form which uses nodemailer. I used Postman to check if my backend is working, and it is. I even get an email in my outlook. However, I am stuck at the front end bit. I just can't seem to get the actual contact form to send an email on submit. My code is below.
Backend
app.use(express.json());
app.use(bodyParser.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
const transporter = nodemailer.createTransport({
service: "hotmail",
auth: {
user: ,
pass: ,
}
});
transporter.verify(function (error, success) {
if (error) {
console.log(error);
} else {
console.log("Server is ready to take our messages");
}
});
app.post('/send', (req, res, next) => {
var name = req.body.name
var email = req.body.email
var subject = req.body.subject
var message = req.body.message
var mail = {
from: name,
to: ,
subject: subject,
text: message
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
})
Frontend
import axios from "axios";
import React from 'react';
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
subject: '',
message: ''
}
}
onNameChange(event) {
this.setState({ name: event.target.value })
}
onEmailChange(event) {
this.setState({ email: event.target.value })
}
onSubjectChange(event) {
this.setState({ subject: event.target.value })
}
onMsgChange(event) {
this.setState({ message: event.target.value })
}
submitEmail(e) {
e.preventDefault();
axios({
method: "POST",
url: "/send",
data: this.state
}).then((response) => {
if (response.data.status === 'success') {
alert("Message Sent.");
this.resetForm()
} else if (response.data.status === 'fail') {
alert("Message failed to send.")
}
})
}
resetForm() {
this.setState({ name: '', email: '', subject: '', message: '' })
}
render() {
return (
<div className="section">
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="section-title">
<h2 className="title">Contact Us</h2>
<p>Let us know what you think! In order to provide better service,
please do not hesitate to give us your feedback. Thank you.</p><hr />
<form id="contact-form" onSubmit={this.submitEmail.bind(this)}
method="POST">
<div className="form-group">
<div className="row">
<div className="col-md-6">
<input placeholder="Name" id="name" type="text"
className="form-control" required value={this.state.name}
onChange={this.onNameChange.bind(this)} />
</div>
<div className="col-md-6">
<input placeholder="Email" id="email" type="email"
className="form-control" aria-describedby="emailHelp"
required value={this.state.email} onChange=
{this.onEmailChange.bind(this)} />
</div>
</div>
</div>
<div className="form-group">
<input placeholder="Subject" id="subject" type="text"
className="form-control" required value={this.state.subject}
onChange={this.onSubjectChange.bind(this)} />
</div>
<div className="form-group">
<textarea placeholder="Message" id="message"
className="form-control" rows="1"
required value={this.state.message}
onChange={this.onMsgChange.bind(this)} />
</div>
<button type="submit" className="primary-btn submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ContactForm;

Extra undefined value in this.state

i am trying to post a form in reactjs, and i suspect it doesnt write to DB because i get strange undefined in my state, which looks like:
form looks like this
but in console i get:
this
my code on front is :
constructor(props) {
super(props);
this.state = { name: '', gender: '', email: '' };
}
handleChange= (event) => {
this.setState({
[event.target.name]: event.target.value,
[event.target.gender]: event.target.value,
[event.target.email]: event.target.value,
// [event.target.phone]: event.target.value,
});
}
handleSubmit = (event) => {
console.log(JSON.stringify(this.state));
alert('A form was submitted: ' + this.state);
fetch('http://localhost:3000/api/game/contacts', {
method: 'POST',
body: JSON.stringify(this.state)
}).then(function(response) {
return response.json();
});
event.preventDefault();
}
render() {
const { user } = this.props.auth;
console.log(this.state);
return(
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name:</label>
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
<label>
Gender:</label>
<input type="text" value={this.state.value} name="gender" onChange={this.handleChange} />
<label>
Email:</label>
<input type="text" value={this.state.value} name="email" onChange={this.handleChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
Dashboard.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = ( state ) => ({
auth: state.auth
});
export default connect( mapStateToProps )( Dashboard );
must be super simple, but i googled for 2 hours, and could not see issue. Thanks for you time

ComboBox doesn't show after setState or forceUpdate

my problem is that I want to get info If I'm authorized from API using axios.get before rendering the page. I did something like that. Everything is working perfectly but my with a role to choose doesn't show.
I'm new in react. "this.forceUpdate()" <- same problem
If I delete my authorization check, eliminate const{authorized} = this.state and {authorized ?(...) I see the combobox.
class RegisterComponent extends Component {
componentDidMount() {
this.checkAuthorizationStatus();
M.AutoInit();
}
checkAuthorizationStatus(){
axios.get(API_URL+`/logged_in`)
.then(response=>{
if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
this.setState({authorized:true})
}
else{
return <Redirect to="/login" />
}
})
}
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
role : 'ROLE_ADMIN',
hasCreationFailed: false,
showSuccessMessage: false,
authorized : false,
}
}
handleChange = (event) => {
this.setState(
{
[event.target.name]: event.target.value
}
)
}
submitClicked = () => {
console.log({login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]})
axios.post(API_URL + '/admin/register', {
login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]
})
.then((response) => {
this.setState({
showSuccessMessage: true,
hasCreationFailed: false
}
)
console.log(response)
})
.catch((error) => {
this.setState({
showSuccessMessage: false,
hasCreationFailed: true
})
console.log(error)
})
}
render() {
const{authorized} = this.state
return (
<React.Fragment>
{authorized ?(
<div className="row container">
<div className="col s10 offset-s1 l4 offset-l4">
<div className="purple-text accent-2"><h5>Create New Account</h5></div>
<div className="input-field">
<select value={this.state.role} onChange={this.handleChange} name="role">
<option value='ROLE_ADMIN'>Administrator</option>
<option value='ROLE_TABLE'>Klient</option>
<option value='ROLE_WORKER'>Pracownik</option>
</select>
</div>
<div className="input-field">
<input className="validate" type="text" id="username" name="username"
value={this.state.username} onChange={this.handleChange}/>
<label htmlFor="username">Username</label>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" value={this.state.password}
onChange={this.handleChange}/>
</div>
<button className="btn blue col l12 waves-effect waves-light"
onClick={this.submitClicked}>Zarejestruj użytkownika
</button>
{this.state.showSuccessMessage &&
<div className="green-text">Rejestracja zakończona powodzeniem</div>}
{this.state.hasCreationFailed && <div className="red-text">Rejestracja nie powiodła się</div>}
</div>
</div>
):(<></>)}
</React.Fragment>
)}
}
export default RegisterComponent
Could anyone help me?
Update the role property of state in your handleChange since your <select> uses value from this.state.role
handleChange = (event) => {
this.setState(
{
role: event.target.value // update 'role' property
}
)
}

ReactJS - how can I handle notifications to user based on server response?

so I've been trying to figure out
how to handle some notifications/alerts to show users some information based on what they typed in for example login form.
const DoLogin = async (email, password) => {
const loginTeacher = await axios.post(
"http://localhost:3000/teachers/login",
{
email,
password
}
);
return loginTeacher;
};
class Login extends React.Component {
state = {
email: "",
password: "",
logged: false,
status: "",
errorMessage: ""
};
onEmailChange = e => {
this.setState({
email: e.target.value
});
};
onPassChange = e => {
this.setState({
password: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
DoLogin(this.state.email, this.state.password)
.then(res => {
localStorage.setItem("mysecrettoken", res.data.token);
this.setState({ teacher: res.data, logged: true, status: res.status });
alert("Successfully logged in");
})
.catch(err => {
alert("Unable to login in, user not found");
});
};
loginForm() {
return (
<div className="Login form">
<form onSubmit={this.onSubmit}>
<label htmlFor="email">
Email:
<input
type="text"
name="email"
value={this.state.email}
onChange={this.onEmailChange}
/>
</label>
<br />
<label htmlFor="password">
Hasło:
<input
type="password"
name="password"
value={this.state.password}
onChange={this.onPassChange}
/>
</label>
<br />
<input type="submit" value="Zaloguj" />
<input type="button" value="Dodaj nauczyciela" />
</form>
</div>
);
}
}
Now, whenever a user is able to login it shows alert with the message, but I don't think that's a good way to show user information.
Could you please help me with that? Some articles/libraries would be great. I've tried to implement react toast but I failed to do that.
You can store the details in the state (like you already do) and then access in the render method for conditional rendering if the user has logged in.
const DoLogin = async (email, password) => {
const loginTeacher = await axios.post(
"http://localhost:3000/teachers/login",
{
email,
password
}
);
return loginTeacher;
};
class Login extends React.Component {
state = {
email: "",
password: "",
logged: false,
status: "",
errorMessage: ""
};
onEmailChange = e => {
this.setState({
email: e.target.value
});
};
onPassChange = e => {
this.setState({
password: e.target.value
});
};
onSubmit = e => {
e.preventDefault();
DoLogin(this.state.email, this.state.password)
.then(res => {
localStorage.setItem("mysecrettoken", res.data.token);
this.setState({ teacher: res.data, logged: true, status: res.status, showingMessage: true });
setTimeout(() => {
this.setState({ showingMessage: false })
}, 2000)
alert("Successfully logged in");
})
.catch(err => {
// update state with ERROR
this.setState({ error: err.message })
alert("Unable to login in, user not found");
});
};
loginForm() {
if (this.state.logged && this.state.showingMessage) {
return (<div>You've logged in as {this.state.teacher.name}</div>)
}
return (
<div className="Login form">
{/* display ERROR */}
{this.state.error && <span style="color:red">
There was an error during registration: {this.state.error}.
</span>}
<form onSubmit={this.onSubmit}>
<label htmlFor="email">
Email:
<input
type="text"
name="email"
value={this.state.email}
onChange={this.onEmailChange}
/>
</label>
<br />
<label htmlFor="password">
Hasło:
<input
type="password"
name="password"
value={this.state.password}
onChange={this.onPassChange}
/>
</label>
<br />
<input type="submit" value="Zaloguj" />
<input type="button" value="Dodaj nauczyciela" />
</form>
</div>
);
}
}
I don't know where your render method is, but basically just access the state. You can also set a timeout after you received the data, and add another property on the state, like showingMessage which will be true at first, and then in say 2s will be false, then your condition would be if (this.state.logged & this.state.showingMessage).

Getting data from SQL Server database in onClick event on React using vs2017

I am on the beginning of my programming and that's my duty to code a forum web page with login. After login I am supposed to put come content and they should be editable but I am still on the beginning. I would be really happy if someone can help because right now I need to put the data into the database (I am able to get data drom the database I can consolo them)
It is really hard coding :(
But how to get the form to the database :/
This is tsx file on frontend side.
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
//import { Link, NavLink } from 'react-router-dom';
export class SignUp extends React.Component<RouteComponentProps<{}>, {}> {
constructor(props: RouteComponentProps<{}> | undefined) {
super(props);
this.state = {
name: '',
surname: '',
username: '',
email: '',
password: ''
};
this.handleNameChange = this.handleNameChange.bind(this);
this.handleSurnameChange = this.handleSurnameChange.bind(this);
}
handleNameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ name: e.target.value });
}
handleSurnameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ surname: e.target.value });
}
handleSubmit(e: any) {
e.preventDefault();
const formKayit = {
name: this.state.name,
surname: this.state.surname
};
console.log("uye oldunuz", formKayit);
}
public render() {
return (
<div>
<h1>We are glad to see you here. </h1>
<form >
<label>
Name:
<input className="form-control" type="text" onChange={(e) => { this.handleNameChange(name); }} //name="Name" value={this.state.Name} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<label>
Surname:
<input className="form-control" type="text" onChange={(e) => { this.handleSurnameChange(e); }} //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
Username:
<input className="form-control" type="text" //name="Username" value={this.state.Username} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
E-mail:
<input className="form-control" type="text" //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<label>
Password:
<input className="form-control" type="password" //name="Password" value={this.state.Password} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<button onClick={(e) => { this.handleSubmit(e); }} className="btn">SignUp </button>
</div>
</form>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Resources