I am new in react and trying to send post request to an api and getting state undefined while sending post request from react app, i this occurs because state stores data as an object. Dont know how to solve this. i would really appreciate some help.
compmonent.js
import React, { Component } from 'react'
class Register extends Component {
register () {
// alert('register')
console.warn('state', this.state)
fetch('http://localhost:8000/api/v1/accounts/registration/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then((result) => {
result.json().then((resp) => {
console.log(resp.data.token)
localStorage.setItem('register', JSON.stringify(resp.data.token))
})
})
}
render () {
return (
<div>
<div>
<label>Email</label>
<input
type='text' placeholder='email'
onChange={(e) => { this.setState({ email: e.target.value }) }}
/><br /><br />
<label>First name</label>
<input
type='text' placeholder='first name'
onChange={(e) => { this.setState({ first_name: e.target.value }) }}
/><br /><br />
<label>Last name</label>
<input
type='text' placeholder='last name'
onChange={(e) => { this.setState({ last_name: e.target.value }) }}
/><br /><br />
<label>Password</label>
<input
type='password' placeholder='password'
onChange={(e) => { this.setState({ password1: e.target.value }) }}
/><br /><br />
<label>Confirm password</label>
<input
type='password' placeholder='confirm password'
onChange={(e) => { this.setState({ password2: e.target.value }) }}
/><br /><br />
<button onClick={() => this.register()}>Register</button>
</div>
</div>
)
}
}
export default Register
thanks
Your code looks ok,
I've created a runnable code snippet from your code, only time state is null and not undefined, is when you don't fill-up the form and submit,
for that you can put a condition before making fetch request.
You can run the below code snippet and check :
class App extends React.Component {
register () {
// alert('register')
console.warn('state', this.state)
if (this.state) { // <------ HERE
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
// Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
}).then((result) => {
result.json().then((resp) => {
console.log(resp.data.token)
localStorage.setItem('register', JSON.stringify(resp.data.token))
})
})
}
}
render () {
return (
<div>
<div>
<label>Email</label>
<input
type='text' placeholder='email'
onChange={(e) => { this.setState({ email: e.target.value }) }}
/><br /><br />
<label>First name</label>
<input
type='text' placeholder='first name'
onChange={(e) => { this.setState({ first_name: e.target.value }) }}
/><br /><br />
<label>Last name</label>
<input
type='text' placeholder='last name'
onChange={(e) => { this.setState({ last_name: e.target.value }) }}
/><br /><br />
<label>Password</label>
<input
type='password' placeholder='password'
onChange={(e) => { this.setState({ password1: e.target.value }) }}
/><br /><br />
<label>Confirm password</label>
<input
type='password' placeholder='confirm password'
onChange={(e) => { this.setState({ password2: e.target.value }) }}
/><br /><br />
<button onClick={() => this.register()}>Register</button>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
Related
This the component I created. I can get the contact in console but throws error on submission. I can post the data through Postman; the problem occurs when I submit the form. Where is the error in the handlesubmit function?
import axios from 'axios';
import React, { useState } from 'react';
const ContactForm = () => {
const [contact, setContact] = useState({
firstName: '',
lastName: '',
phoneNumber: '',
email: '',
message: '',
});
function handleChange(e) {
setContact({ ...contact, [e.target.name]: [e.target.value] });
}
function hanhdleSubmit(e) {
e.preventDefault();
console.log(contact);
axios
.post('http://localhost:8080/contact', contact)
.then((response) => {
console.log('Response after post api', response.data);
})
.catch((error) => {
console.log('Error while post api', error);
});
}
return (
<div className="box poptrox-popup ">
<form onSubmit={hanhdleSubmit} noValidate>
<div className="row gtr-uniform">
<div className="col-6 col-12-xsmall">
<input
type="text"
placeholder="First Name"
value={contact.firstName}
name="firstName"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="text"
placeholder="Last Name"
value={contact.lastName}
name="lastName"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="tel"
placeholder="Phone Number"
value={contact.phoneNumber}
name="phoneNumber"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<input
type="email"
placeholder="Email"
value={contact.email}
name="email"
onChange={handleChange}
autoComplete="off"
/>
<br />
</div>
<div className="col-6 col-12-xsmall">
<textarea
placeholder="Please type what you are looking from us?"
value={contact.message}
name="message"
onChange={handleChange}
/>
<br />
</div>
<div className="col-12">
<button type="submit">Submit</button>
<h1>First Name:{contact.firstName}</h1>
<h1>Last Name:{contact.lastName}</h1>
<h1>Phone Number:{contact.phoneNumber}</h1>
<h1>Email:{contact.email}</h1>
<h1>message:{contact.message}</h1>
</div>
</div>
</form>
</div>
);
};
export default ContactForm;
This is the error I'm getting:
{
"timestamp": "2020-12-04T18:32:39.945+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/contact"
}
I think it's the syntax of the body sent to the backend, the second parameter of your axios.post should be an object :
axios
.post('http://localhost:8080/contact', contact)
should be
axios
.post('http://localhost:8080/contact', { contact })
Here is my code for my login page that I want to use to redirect onto a profile page:
import React, { Component } from "react";
export default class Login extends Component {
constructor(props){
super(props)
this.state = {
username: '',
password: '',
}
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
const {username, password} = this.state;
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => result.json())
.then((info) => {console.log(info)})
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form onSubmit={this.handleSubmit}>
<h3>Sign In</h3>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Enter email" value={this.state.value} onChange={this.handleChange} name="username" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" value={this.state.value} onChange={this.handleChange} placeholder="Enter password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Submit</button>
<p className="forgot-password text-right">
Forgot password?
</p>
</form>
</div>
</div>
);
}
}
import React, { Component } from "react";
import { Redirect } from 'react-router';
import { withRouter } from 'react-router';
export default class SignUp extends Component {
constructor(props){
super(props)
this.state = {
firstName: '',
password: '',
username: '',
lastName: '',
email: '',
isAdmin: 'false',
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
console.log(this.state.email)
console.log(this.state.isAdmin)
}
onSubmit = async (e) => {
e.preventDefault();
await this.state.isAdmin == "on" ? this.setState({isAdmin: true}) : this.setState({isAdmin: false})
// const {firstName, lastName, email,} = this.state;
fetch('http://localhost:9000/users/new', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state)
})
.then((info) => {console.log(info)})
this.props.history.push('/profile');
}
render() {
return (
<div className="auth-wrapper">
<div className="auth-inner">
<form method='POST' action='http://localhost:9000/users/new'>
<h3>Sign Up</h3>
<div className="form-group">
<label>First name</label>
<input type="text" className="form-control" placeholder="First name" name ="firstName"/>
</div>
<div className="form-group">
<label>Last name</label>
<input type="text" className="form-control" placeholder="Last name" name="lastName" />
</div>
<div className="form-group">
<label>Username</label>
<input type="text" className="form-control" placeholder="Username" name="username" />
</div>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" name="email" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" name="password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" onClick={console.log(this.state.value)} name="isAdmin" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Signup as Reviewer</label>
</div>
</div>
<button type="submit" className="btn btn-primary btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
</div>
</div>
);
}
}
When I click my profile page I want to redirect to /profile. At the moment it hangs and successfully logs in the user. I have to manually go to /profile to reach the page right now
I am using Express as my backend FYI
Edit: I have added my sign up page code as that is not working also and not sure why. Like the login page it hangs
try this
fetch('http://localhost:9000/users/login', {
method: "POST",
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(this.state),
})
.then((result) => {
result.json();
this.props.history.push("/Profile");})
.then((info) => {console.log(info)})
I am not being able to change input fields.Any suggestion?
const MiddlePanel = ({ user }) => {
const history = useHistory();
const [data, setData] = useState({
firstname: '',
lastname: '',
email: '',
phoneNo: '',
});
const { firstname, lastname, email, phoneNo } = data;
useEffect(() => {
const fetchUser = async () => {
const res = await axios.get(`http://localhost:5000/users/${user._id}`);
setData({
firstname: res.data.firstname,
lastname: res.data.lastname,
email: res.data.email,
password: res.data.password,
});
};
fetchUser();
}, [user._id]);
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
const newUser = { firstname, lastname, email, phoneNo };
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(newUser);
await axios.patch(
`http://localhost:5000/users/${user._id}`,
body,
config
);
history.push("/");
} catch (err) {}
};
return (
<div>
<Form onSubmit={handleSubmit}>
<Input
type="text"
name="firstname"
onChange={handleChange}
value={user.firstname}
/>
<Input
type="text"
name="lastname"
onChange={handleChange}
value={user.lastname}
/>
<Input
type="email"
name="email"
onChange={handleChange}
value={user.email}
/>
<Input
type="tel"
name="phoneNo"
onChange={handleChange}
value={user.phoneNo}
/>
<PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
Update
</PrimaryButton>
</Form>
</div>
);
};
I think you should use data.firstname instead of user for the value property
<div>
<Form onSubmit={handleSubmit}>
<Input
type="text"
name="firstname"
onChange={handleChange}
value={data.firstname}
/>
<Input
type="text"
name="lastname"
onChange={handleChange}
value={data.lastname}
/>
<Input
type="email"
name="email"
onChange={handleChange}
value={data.email}
/>
<Input
type="tel"
name="phoneNo"
onChange={handleChange}
value={data.phoneNo}
/>
<PrimaryButton className="btn btn-primary" style={{ width: "100%" }}>
Update
</PrimaryButton>
</Form>
</div>
I am creating a react program for front-end which makes a api call when a form is submitted, I want the contents of the form to be sent in JSON format
Back-end code works fine, back-end is written in python and it works fine when I test using postman.
import React, { Component } from "react"
class MainCon extends Component {
constructor() {
super()
this.state = {
systemId: "",
password: "",
systemType: "",
ip: "",
portNumber: "",
sourceAddressTon: "",
sourceAddressNpi: "",
sourceAddress: "",
destinationAddressTon: "",
destinationAddressNpi: "",
destinationAddress: "",
registeredDelivery: "",
dataCoding: "",
shortMessage: "",
id: "",
//isFriendly: false,
messageMethod: "",
//favColor: "blue"
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
//const {name, value, type, checked} = event.target
// type === "checkbox" ? this.setState({ [name]: checked }) : this.setState({ [name]: value })
const { name, value } = event.target
this.setState({ [name]: value })
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
console.log(event.target);
let object = {}
for (const [key, value] of data.entries()) {
object[key] = value
}
/*
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = {
method: 'POST',
headers,
body: JSON.stringify(object),
};
const request = new Request('http://127.0.0.1:5000/api/add_message', options);
const response = fetch(response);
const status = response.status;
if (status === 201) {
this.fetchAll()
}
*/
fetch('http://127.0.0.1:5000/api/add_message/', {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(object),
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<br />
<label htmlFor="systemId">System ID</label>
<input
type="text"
value={this.state.systemId}
name="systemId"
placeholder="System ID"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="password">Password:</label>
<input
type="text"
value={this.state.password}
name="password"
placeholder="Password"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="systemType">System Type:</label>
<input
type="text"
value={this.state.systemType}
name="systemType"
placeholder="System Type"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="ip">IP:</label>
<input
type="text"
value={this.state.ip}
name="ip"
placeholder="IP"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="portNumber">Port Number:</label>
<input
type="text"
value={this.state.portNumber}
name="portNumber"
placeholder="Port Number"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddressTon">Source Address Ton:</label>
<input
type="text"
value={this.state.sourceAddressTon}
name="sourceAddressTon"
placeholder="Source Address Ton"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddressNpi">Source Address Npi:</label>
<input
type="text"
value={this.state.sourceAddressNpi}
name="sourceAddressNpi"
placeholder="Source Address Npi"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="sourceAddress">Source Address:</label>
<input
type="text"
value={this.state.sourceAddress}
name="sourceAddress"
placeholder="Source Address"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddressTon">Destination Address Ton:</label>
<input
type="text"
value={this.state.destinationAddressTon}
name="destinationAddressTon"
placeholder="Destination Address Ton"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddressNpi">Destination Address Npi:</label>
<input
type="text"
value={this.state.destinationAddressNpi}
name="destinationAddressNpi"
placeholder="Destination Address Npi"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="destinationAddress">Destination Address:</label>
<input
type="text"
value={this.state.destinationAddress}
name="destinationAddress"
placeholder="Destination Address"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="registeredDelivery">Registered Delivery:</label>
<input
type="text"
value={this.state.registeredDelivery}
name="registeredDelivery"
placeholder="Registered Delivery"
onChange={this.handleChange}
/>
<br />
<br />
<label htmlFor="dataCoding">Data Coding:</label>
<input
type="text"
value={this.state.dataCoding}
name="dataCoding"
placeholder="Data Coding"
onChange={this.handleChange}
/>
<br />
<br />
<label>
<input
type="radio"
name="messageMethod"
value="randomMessage"
checked={this.state.messageMethod === "randomMessage"}
onChange={this.handleChange}
/> Random Message
</label>
<label>
<input
type="radio"
name="messageMethod"
value="customMessage"
checked={this.state.messageMethod === "customMessage"}
onChange={this.handleChange}
/> Custom Message
</label>
<br />
<br />
<label htmlFor="shortMessage">Short Message:</label>
<textarea
//className="hideDontTakeUpSpace"
value={this.state.shortMessage}
name="shortMessage"
placeholder="Short Message"
onChange={this.handleChange}
/>
<br />
{/* Formik */}
{/**
<label>Favorite Color:</label>
<select
value={this.state.favColor}
onChange={this.handleChange}
name="favColor"
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
</select>
*/}
{/*<h1>{this.state.systemId} {this.state.password}</h1>*/}
<h2>Type of message: {this.state.messageMethod}</h2>
{/*<h2>Your favorite color is {this.state.favColor}</h2>*/}
<button>Submit</button>
</form>
)
}
}
export default MainCon
This is the server side python code
import requests
import json
from flask import Flask, request, jsonify
from jsonDemoNew import getMemberNew
import redis
app = Flask(__name__)
#app.route('/api/add_message', methods=['GET', 'POST'])
def add_message():
if request.method == 'POST':
content = request.json
print request
print content
return jsonify({"Number of messages sent": 123, "Printed status" : 1})
return "Not POST request"
if __name__ == "__main__":
app.run()
I think there is some problem with the headers I am including
I personally prefer to use axios to make POST requests.
npm install axios --save
Just like on postman:
Select the method ('post' in that case)
Select the url ('http://127.0.0.1:5000/api/add_message/')
Send theData in "json form" like:
{
"data": "oktay"
}
And it's done:
const axios = require('axios');
const postIt = (theData) => {
axios({
method: 'post', // THERE GOES THE METHOD
url: 'http://127.0.0.1:5000/api/add_message/', // THERE GOES THE URL
headers: {},
data: theData
})
.then(function (response) {
console.log("The response of the server: "+response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
postIt({
"data" : "oktay"
});
I'm pretty new with React and Call requests. I'm building a full stack app using React, express, MySql, and Sequelize.
Everything works fine except for the Put request to edit the client information. I'm using Axios to make those calls and I can add, see, and delete data from the app but the edit part is not working.
When hitting the submit button on the form, the Put request is returning an empty array instead of the actual modified data. My routes are Ok (I believe), as testing it with Postman work just fine. I'm almost sure that my problem is on the method being used in the axios call, but I can't just find the right way to make it work. Any help would be highly appreciated.
import React, { Component } from 'react';
import axios from 'axios';
import API from '../../utils/API';
class index extends Component {
constructor(props) {
super(props);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onChangeFirstName = this.onChangeFirstName.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onChangePetName = this.onChangePetName.bind(this);
this.onChangeBreed = this.onChangeBreed.bind(this);
this.onChangeNotes = this.onChangeNotes.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
client: null
}
}
componentDidMount() {
let id = this.props.match.params.id
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
.catch(error => console.log(error))
}
onChangeLastName(e) {
this.setState({
lastName: e.target.value
});
}
onChangeFirstName(e) {
this.setState({
firstName: e.target.value
});
}
onChangePhone(e) {
this.setState({
phone: e.target.value
});
}
onChangePetName(e) {
this.setState({
petName: e.target.value
});
}
onChangeBreed(e) {
this.setState({
breed: e.target.value
});
}
onChangeNotes(e) {
this.setState({
notes: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName.value,
firstName: this.state.client.firstName.value,
phone: this.state.client.phone.value,
petName: this.state.client.petName.value,
breed: this.state.client.breed.value,
notes: this.state.client.notes.value
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
render() {
const client = this.state.client ? (
<div className="client">
<h3 style={{ marginLeft: "60px" }}>Update Client</h3>
<form onSubmit={this.onSubmit} style={{ padding: "60px" }}>
<div className="form-group">
<label>Last Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.lastName}
onChange={this.onChangeLastName}
/>
</div>
<div className="form-group">
<label>First Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.firstName}
onChange={this.onChangeFirstName}
/>
</div>
<div className="form-group">
<label>Phone: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.phone}
onChange={this.onChangePhone}
/>
</div>
<div className="form-group">
<label>Pet Name: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.petName}
onChange={this.onChangePetName}
/>
</div>
<div className="form-group">
<label>Breed: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.breed}
onChange={this.onChangeBreed}
/>
</div>
<div className="form-group">
<label>Notes: </label>
<input type="text"
className="form-control"
defaultValue={this.state.client.notes}
onChange={this.onChangeNotes}
/>
</div>
<br />
<div className="form-group">
<input type="submit" value="Update Client"
className="btn btn-primary" />
</div>
</form>
</div>
) : (
<div className="center">Loading Client</div>
)
return (
<div className="container">
{client}
</div>
)
}
}
export default index;
I am assuming it is because of the way you are handling the onchange of your inputs. You want to set the onchange to the client value in your state. But instead you are setting it to the state itself. So then when you are building your object to send to the backend you are sending null data because you haven't set any data to the actual client value in your state and it is still null. Try console logging the state and you will see what I'm talking about. Also you are adding a .value to the end each of the state values you are trying to build your object with and this is not necessary. Finally you don't need to specify an onchange for each input just give the input a name attribute and you can set your onchange handler like so:
onChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
so your component would look something like the following:
import React, { Component } from 'react';
import axios from 'axios';
import API from '../../utils/API';
class index extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
client: null
}
}
componentDidMount() {
let id = this.props.match.params.id
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
.catch(error => console.log(error))
}
onChange(e) {
this.setState({
client: {
...this.state.client,
[e.target.name]: e.target.value
}
});
}
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName,
firstName: this.state.client.firstName,
phone: this.state.client.phone,
petName: this.state.client.petName,
breed: this.state.client.breed,
notes: this.state.client.notes
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
render() {
const client = this.state.client ? (
<div className="client">
<h3 style={{ marginLeft: "60px" }}>Update Client</h3>
<form onSubmit={this.onSubmit} style={{ padding: "60px" }}>
<div className="form-group">
<label>Last Name: </label>
<input type="text"
name="lastName"
className="form-control"
defaultValue={this.state.client.lastName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>First Name: </label>
<input type="text"
name="firstName"
className="form-control"
defaultValue={this.state.client.firstName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Phone: </label>
<input type="text"
name="phone"
className="form-control"
defaultValue={this.state.client.phone}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Pet Name: </label>
<input type="text"
name="petName"
className="form-control"
defaultValue={this.state.client.petName}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Breed: </label>
<input type="text"
name="breed"
className="form-control"
defaultValue={this.state.client.breed}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label>Notes: </label>
<input type="text"
name="notes"
className="form-control"
defaultValue={this.state.client.notes}
onChange={this.onChange}
/>
</div>
<br />
<div className="form-group">
<input type="submit" value="Update Client"
className="btn btn-primary" />
</div>
</form>
</div>
) : (
<div className="center">Loading Client</div>
)
return (
<div className="container">
{client}
</div>
)
}
}
export default index;
It could be because you're calling this.props.history.push immediately after calling axios.post, essentially redirecting before the POST request has a chance to return a response.
Try putting this.props.history.push('/admin') inside the .then().
You are doing multiple thing wrong here,
For every input you should have only 1 onChange handler, every input have name attribute to work with state. For example,
<input type="text"
className="form-control"
defaultValue={this.state.client.lastName}
name="lastName" //Like this should add name for every input like below
onChange={this.onChangeHandler} //This is a common onChangeHandler for every input should add in every input like below
/>
<input type="text"
className="form-control"
defaultValue={this.state.client.firstName}
name="firstName"
onChange={this.onChangeHandler}
/>
And onChangeHandler function should be,
onChangeHandler(e){
this.setState({
...this.state.client,
[e.target.name]:e.target.value
})
}
And finally your onSubmit function should be,
onSubmit(e) {
e.preventDefault();
let obj = {
lastName: this.state.client.lastName, //Remove `.value` as we are getting values from state and not directly from input
firstName: this.state.client.firstName,
phone: this.state.client.phone,
petName: this.state.client.petName,
breed: this.state.client.breed,
notes: this.state.client.notes
};
let id = this.state.client.id
axios.put("http://localhost:3000/api/clients/" + id, obj)
// .then(alert("client Updated"))
.then(res => console.log(res))
.catch(error => console.log(error))
this.props.history.push('/admin');
}
Note: You won't get value here in console.log,
API.getClient(id)
.then(res => {
this.setState({
client: res.data
})
console.log(this.state.client.id)
})
beacuse seState is async, you should use callback in setState to make console.log,
API.getClient(id)
.then(res => {
this.setState({
client: res.data
}, () => console.log(this.state.client.id)) //This is callback
})