Extra undefined value in this.state - reactjs

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

Related

this.state not populating fields in editProfile.component

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

400 bad request during axios call

Not sure why but the POST request is coming back 400. Postman says my django backend is doing fine. It all happens at the post_flashcards method any help would be great and I am willing to show any other code as requested. although there shouldnt be the need to since this component acts mostly on its own.
class CreateFlashCard extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
collection_id: '',
term: '',
definition: '',
}
this.handleSubmit = this.handleSubmit.bind(this)
}
onChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
this.post_flashcard()
}
async post_flashcard() {
const card = this.state;
const col_id = parseInt(this.state.collection_id)
try{
await axios.post(`http://127.0.0.1:8000/flashcardsapp/${col_id}`, card)
.then(response => console.log(response.status))
}catch(er){
console.log('ERROR in post_flashcard', er)
}
}
render() {
const {title, collection_id, term, definition} = this.state
return (
<form onSubmit={this.handleSubmit}>
<h2>Create a Card</h2>
<label for="title">Enter Collection Title</label>
<input type="text" name="title" value={title} onChange={this.onChange} ></input>
<label for="collection_id">Enter Collection ID</label>
<input type="number" name="collection_id" value={collection_id} onChange={this.onChange} ></input>
<label for="term">Enter Term</label>
<input type="text" name="term" value={term} onChange={this.onChange} ></input>
<label for="definition">Enter Definition</label>
<input type="text" name="definition" value={definition} onChange={this.onChange} ></input>
<input type="submit"></input>
</form>
);
}
}
export default CreateFlashCard;
If you are doing post processing, you can convert the Data to Json format and send it.
var post_data = {
your_post_name: this.state
};
axios
.post(url, JSON.stringify(post_data))
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
or
axios
.post(url,JSON.stringify({your_post_name:this.state}))
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
I solved the issue state had typo in title needed to be collection_title.

Basic Form react

Hello I just want to make a form and my textboxes does not take my inputs and my submit works but sends no values. What am I doing wrong? I know it's a basic question but I don't know what the problem is in my code.
Key problems:
it doesn't update the state nor take my inputs.
fields editable but cant write into them
Code
import React, { Component } from "react";
class Postform extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
category: "",
price: "",
};
}
changeHandler = (e) => {
this.setState = { [e.target.name]: e.target.value };
};
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
};
render() {
const { name, category, price } = this.state;
return (
<div>
<form onSubmit={this.submitHandler}>
<div>
<input
type="text"
name="name"
placeholder="Name"
value={name}
onChange={this.changeHandler}
/>
<input
type="text"
name="category"
placeholder="Category"
value={category}
onChange={this.changeHandler}
/>
<input
type="text"
name="price"
placeholder="Price"
value={price}
onChange={this.changeHandler}
/>
</div>
<button type="submit">Add product</button>
</form>
</div>
);
}
}
export default Postform;
Change this line to
changeHandler = e => {
this.setState({[e.target.name]: e.target.value });
};
Since setState is a function it is not a property !

I can't type in input text using reactjs

i can't change text when typing in input text !
This is my fontend code :
constructor(props) {
super(props);
this.state = {
items: [],
acc_email: '',
acc_nom: '',
acc_prenom: '',
acc_tel: '',
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
the value of input comes from DB using fetch :
componentDidMount(){
const token = localStorage.getItem('toktok');
fetch(`${API}/api/account`,{
method: 'GET',
headers :{
'authorization': `Bearer ${token}`,
}
})
.then(results => {
return results.json();
})
.then(data => {
this.setState({ items: data.result });
console.log("account: ",data.result);
// localStorage.setItem('mymy', "fiss");
// console.log(items);
// console.log(items.length);
})
.catch(err => {
console.log("erroooor : ",err);
});
}
i don't know what's wrong in this function :
handleInputChange = e => {
const name = e.target.name;
const value = e.target.value;
this.setState({[name]: value});
this.setState({ [e.target.name]: e.target.value });
}
and finally, this's the render() that conains all inputs:
<div key={items._id}>
<input type="text" value={items.email} name="acc_email" onChange={this.handleInputChange} />
<input type="text" value={items.nom} name="acc_nom" onChange={this.handleInputChange} />
<input type="text" value={items.prenom} name="acc_prenom" onChange={this.handleInputChange} />
<input type="text" value={items.tel} name="acc_tel" onChange={this.handleInputChange} />
<a className="admin-btn-update" href={`/updateaccount/${items._id}`}>Modifier</a>
</div>
change value to defaultValue as follows.
<input type="text" defaultValue={items.email} name="acc_email" onChange={this.handleInputChange} />
You are explicitly setting the values of the inputs to be items.email, items.nom.. which makes them controlled inputs, which basically means that it's the component responsibility to control what happens to those inputs.
Since you already implemented the part that updates the component state, all you need to do is to make the inputs values reflect this state:
<input type="text" value={this.state.acc_email} name="acc_email" onChange={this.handleInputChange} />
<input type="text" value={this.state.acc_nom} name="acc_nom" onChange={this.handleInputChange} />
<input type="text" value={this.state.acc_prenom} name="acc_prenom" onChange={this.handleInputChange} />
<input type="text" value={this.state.acc_tel} name="acc_tel" onChange={this.handleInputChange} />

How do I set the state of a parent from a child in react?

I am making a form wizard in React Js. In the first step, I want to hide/display a form base on radio input value. I want to set the state of the parent based on the input from a visible form. Basically, I want to check if a user exists or not and then take the appropriate action. If they exist, I enter their username, if not I enter the registration details. Here is my code
class Step1 extends React.Component {
constructor(props) {
super(props);
this.state = {
userExists: 'false',
username: '',
register: {
full_name: '',
phone_number: '',
id_number: '',
gender: ''
},
submitted: false,
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUserExistsCheck = this.handleUserExistsCheck.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({
[name]: value
});
}
handleUsernameChange(event) {
const { name, value } = event.target;
const { username} = this.state;
this.setState({
username: username
});
}
handleRegisterChange(event) {
const { register } = this.state;
const { name, value } = event.target;
this.setState({
register: {
...register,
[name]: value
}
});
}
handleUserExistsCheck(event) {
this.setState({
...this.state,
userExists: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
...this.state,
submitted: true
});
// TODO: Dispatch based on checkbox
}
_validate() {
let { user } = this.state
this.props.afterValid({
// TODO submit data to wizard
});
}
handleReset() {
this.setState({
...this.state,
userExists: false,
username: '',
full_name: '',
phone_number: '',
id_number: '',
gender: '',
submitted: false,
});
}
render() {
if (this.props.currentStep !== 1) {
return null;
}
const { userExists, username, register } = this.state;
console.log(register)
return(
<div>
<CardHeader>Does the user have an account?</CardHeader>
<CardBody>
<form onSubmit={this.handleSubmit}>
<div>
<input type="radio" value="true" checked={ userExists ==="true"}
onChange={this.handleUserExistsCheck} name="userExists"/> Yes
{' '}
<input type="radio" value="false" checked={ userExists ==="false"}
onChange={this.handleUserExistsCheck} name="userExists"/> No
</div>
{' '}
<PersonalDetails register={register}
username={username}
handleRegisterChange={this.handleRegisterChange}
handleUsernameChange={this.handleUsernameChange}
userExists={userExists}/>
{' '}
<div className="clearfix">
<button type="submit" className="btn btn-primary mb-2 float-right">Next</button>
</div>
</form>
</CardBody>
</div>
);
}
}
function UsernameForm(props) {
return (
<FormGroup>
<label>Username</label>
<Input type="text" name="username" value={props.username}
onChange={props.onChange} placeholder="Username"/>
</FormGroup>
)
}
function RegisterForm(props) {
return(
<div>
<FormGroup>
<label>Full Name</label>
<Input type="text" name="full_name" value={props.register.full_name}
onChange={props.onChange} placeholder="Full Name"/>
</FormGroup>
<FormGroup>
<label>Phone Number</label>
<Input type="text" name="phone_number" value={props.register.phone_number}
onChange={props.onChange} placeholder="Phone Number"/>
</FormGroup>
<FormGroup>
<label>ID Number</label>
<Input type="text" name="id_number" value={props.register.id_number}
onChange={props.onChange} placeholder="ID Number"/>
</FormGroup>
<FormGroup>
<label htmlFor="gender">Gender</label>
<select value={props.register.gender} onChange={props.onChange}
className="custom-select custom-select-lg mb-3" name="gender">
<option value="">----</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</FormGroup>
</div>
);
}
function str2bool(value) {
if (typeof(value) === 'string') {
if (value.toLowerCase() === 'true') return true;
if (value.toLowerCase() === 'false') return false;
}
return value;
}
function PersonalDetails(props) {
let { userExists } = props;
userExists = str2bool(userExists);
if (userExists == true) {
return <UsernameForm username={props.username} onChange={props.handleUsernameChange}/>
} else {
return <RegisterForm register={props.register} onChange={props.handleRegisterChange}/>
}
}
const connectedStep1 = connect(null, null)(Step1);
export { connectedStep1 as Step1 };
Currently, I am getting the error Uncaught TypeError: Cannot read property 'state' of undefined
Create a method in the parent component to update the state, then pass this method to the child component as a prop. When you call this prop in the child it will update the parent state.

Resources