I have blockchain application and created Reactjs interface to send data from user to application but when i enter data and try send it get error as follow , any one can help me?
The error is :
XHR POST http://localhost:3000/api/MedicalRecord
[HTTP/1.1 422 Unprocessable Entity 19ms]
The App.js file as follow
import React, { Component } from 'react';
import PostForm from './PostForm'
function App() {
return (
<div className="App">
<PostForm></PostForm>
</div>
);
}
export default App;
The PostForm.js file as follow
import React, { Component } from 'react'
import axios from 'axios'
class PostRecords extends Component {
constructor(props){
super(props)
this.state = {
record_Id: "",
patient: "",
doctor: "",
description: "",
prescription: ""
}
}
handleChange =(e) =>{
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
axios.post('http://localhost:3000/api/MedicalRecord')
.then(response =>{
console.log(response)
})
}
render() {
const {record_id, patient, doctor, description, prescription} = this.state
return (
<div>
<form onSubmit={this.handleSubmit}>
<div>
<label>record_id :</label>
<input
type='text'
name ='record_id'
value={record_id}
onChange={this.handleChange}
></input>
</div>
<div>
<label>patient :</label>
<input
type='text'
name ='patient'
value={patient}
onChange={this.handleChange}
></input>
</div>
<div>
<label>doctor :</label>
<input
type='text'
name ='doctor'
value={doctor}
onChange={this.handleChange}
></input>
</div>
<div>
<label>description :</label>
<input
type='text'
name ='description'
value={description}
onChange={this.handleChange}
></input>
</div>
<div>
<label>prescription :</label>
<input
type='text'
name ='prescription'
value={prescription}
onChange={this.handleChange}
></input>
</div>
<button type='submit'>Submit Now</button>
</form>
</div>
)
}
}
export default PostRecords
Related
I am trying to build an E commerce web app where I handle the payments. First I need to take shipping information. I have successfully inserted data into mongo but I could not pass the data into another js right away from a single click.
Here is my create address page.
import React, { Component } from 'react'
import '../App.css'
import axios from 'axios'
export default class CreateAddress extends Component {
constructor(props) {
super(props);
this.state = {
address: "",
city: "",
phoneNo:"",
postalCode: "",
country: ""
}
}
handleInputChange = (e)=>{
const {name,value} = e.target;
this.setState({
...this.state,
[name]:value
})
}
onSubmit = (e)=>{
e.preventDefault();
const {address,city,phoneNo,postalCode,country} = this.state;
const data = {
address: address,
city: city,
phoneNo: phoneNo,
postalCode: postalCode,
country: country
}
console.log(data)
axios.post("http://localhost:5000/address/save",data).then((res)=>{
if(res.data.success){
this.setState(
{address: "",
city: "",
phoneNo:"",
postalCode: "",
country: ""}
)
alert("Shipping info added successfully");
}
})
}
render() {
return (
<div className="row wrapper">
<div className="col-10 col-lg-5">
<form className="shadow-lg" >
<h1 className="mb-4">Shipping Info</h1>
<div className="form-group">
<label htmlFor="address_field">Address</label>
<input
type="text"
id="address_field"
className="form-control"
name='address'
value={this.state.address}
onChange={this.handleInputChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="city_field">City</label>
<input
type="text"
id="city_field"
className="form-control"
name='city'
value={this.state.city}
onChange={this.handleInputChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="phone_field">Phone No</label>
<input
type="phone"
id="phone_field"
className="form-control"
name='phoneNo'
value={this.state.phoneNo}
onChange={this.handleInputChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="postal_code_field">Postal Code</label>
<input
type="number"
id="postal_code_field"
className="form-control"
name='postalCode'
value={this.state.postalCode}
onChange={this.handleInputChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="country_field">Country</label>
<input
type = "text"
id="country_field"
className="form-control"
name='country'
value={this.state.country}
onChange={this.handleInputChange}
required
/>
</div>
<button
id="shipping_btn"
type="submit"
className="btn btn-block py-3"
onClick={this.onSubmit}
>
SAVE
</button>
<button id="shipping_btn" type="submit" className = "btn btn-block py-3"><a href = "/confirm" style={{textDecoration:'none',color:'white'}}>PROCEED</a></button>
</form>
</div>
</div>
)
}
}
Once I clicked the PROCEED button the data should direct into /confirm page
You can use react-router to move between different routes in React. Also, in your code when you are sending a post request on onSubmit method, you are clearing the state information, which I think needs to be handled in the confirm page since you need the data in that page also.
Here's a codesandbox demonstrating how you can send the information to another page, using react-router. I've used the functional components, but the concepts works for the class based components also.
note: also you should use onSubmit handler of the form to submit values rather than using the onClick method of the button. Otherwise you force users to click the button to submit the form.
You can use history API to pass data as a URL and grab it into confirm page.
history.push(`/confirmPage?city=${city}&postalCode=${postalCode}`)
in confirmPage.js you will get that data as props
export default class ConfirmPage extends Component{
render(){
const {city, postalCode } = this.props.location.query;
return (
<div>{postalCode}</div>
)
}
I have 3 components: App, CV and EXP_FORM.
APP have state where i store data from EXP_FORM and after that i render it by CV component. Issue is when i type in input fields in EXP_FORM CV updates it in one step behind.
for example: if i type in position input field in EXP_FORM "soft" in CV i will got "sof"
app.js
import React,{Component} from "react";
import CV from "./components/CV"
import EXP_FORM from "./components/Exp_form";
class App extends Component {
constructor(){
super()
this.state = {
name: '',
email: '',
phone: '',
//educationLs:[],
experienceLs:[{id:0}],
}
this.handleChange = this.handleChange.bind(this)
this.handleExp = this.handleExp.bind(this)
}
form_style = {
display: 'grid'
}
handleChange(event){
this.setState({
[event.target.id] : event.target.value
})
}
handleExp = (exp) => {
this.setState({
experienceLs: this.state.experienceLs.map(u => u.id !== exp.id ? u : exp),
})
}
render(){
const {name, email, phone, educationLs,experienceLs} = this.state
return (
<div>
<form style={this.form_style}>
<label htmlFor='nameInput'>Name: </label>
<input type='text' id='name' onChange={this.handleChange}/>
<label htmlFor='emailInput'>Email: </label>
<input type='text' id='email' onChange={this.handleChange}/>
<label htmlFor='phoneInput'>Phone: </label>
<input type='text' id='phone' onChange={this.handleChange}/>
</form>
<EXP_FORM id={0} callback={this.handleExp}/>
<div>
<CV name={name} email={email} phone={phone} exp={experienceLs} />
</div>
</div>
)
}
}
export default App;
EXP_FORM.js
import React from 'react'
class EXP_FORM extends React.Component {
constructor(props){
super(props)
this.state = {
id: props.id,
position: '',
company: '',
city:'',
from: '',
to: ''
}
this.handleChange = this.handleChange.bind(this)
}
form_style = {
display:'grid'
}
handleChange(event){
this.setState({
[event.target.name] : event.target.value
})
}
onTrigger = () => {
this.props.callback(this.state)
}
onChangeEvents = (event) => {
this.handleChange(event)
this.onTrigger()
}
render(){
const {position} = this.state
return(
<div>
<form style={this.form_style} onChange={this.onChangeEvents}>
<label htmlFor='position'>Position: {position}</label>
<input type='text' name='position'/>
<label htmlFor='company'>Company: </label>
<input type='text' name='company'/>
<label htmlFor='city'>City: </label>
<input type='text' name='city'/>
<label htmlFor='from'>From: </label>
<input type='text' name='from'/>
<label htmlFor='to'>To: </label>
<input type='text' name='to'/>
</form>
</div>
)
}
}
export default EXP_FORM
CV.js
import React from "react"
const CV = (props)=>{
const exp = props.exp.map((e) =>
<div key={e.id}>
<p>position: {e.position}</p>
<p>in {e.company}</p>
<p>From {e.from} until {e.to}</p>
<p>city:{e.city}</p>
</div>);
return(
<div>
<h1>Name: <span>{props.name}</span></h1>
<h1>Email: <span>{props.email}</span></h1>
<h1>Phone: <span>{props.phone}</span></h1>
<h1>Experience:</h1>
{exp}
</div>
)
}
export default CV
whats wrong ?
I have three inputs, and I want each input's data to be stored in a state. For example, the name input should be stored in the name state, because I'll need it later to push the three states' values in a firebase database.
I used the onChange function to store the data, but I didn't know how to make each input's function relative to the state I want to put it in.
import React from "react";
import ReactDOM from "react-dom";
export default class Inputs extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
age: ""
};
}
handleChange = e => {
this.setState({ name: e.target.value });
};
render() {
return (
<div>
<form>
<label>
name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<label>
email:
<input type="text" name="email" onChange={this.handleChange} />
</label>
<label>
age:
<input type="text" name="age" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<textarea value={this.state.value} onChange={this.handleChange} />
<button onClick={() => this.props.onClick(this.state.value)}>
Add task
</button>
</div>
);
}
}
getChanges = (e) => {
console.log(e);
this.setState({[e.target.name]: e.target.value}, function () {
console.log(this.state)
})
};
call this function,
<Input onChange={(e) => this.getChanges(e)} name={'name'}
value={this.state.name} placeholder={'Name'}/>
You can pass key and value
<input type="text" name="name" onChange={(event)=>this.handleChange(event,'name')} />
and in your function you can do something like this
handleChange = (e,key) => {
this.setState({ [key] : e.target.value });
};
I have a child component with a select form element, this queries my API and makes a select box out of the data. I then try to pass the option back that's been selected via an OnChange function to my parent component so I can then send my data back to the server. I keep getting an error saying state is not defined, I am new to react and can't see where I am going wrong.
Here is my parent component
var ReactDom = require('react-dom');
const uuid = require('uuid/v1');
import {postDataTest} from "../actions/postData";
import TeamSelectBox from "./TeamSelectBox";
import React, {Component, PropTypes} from "react";
class PlayerForm extends Component {
constructor(props) {
super(props);
this.state = {
teamId: ''
};
this.handleChange = this.handleChange.bind(this);
}
fieldValues = {
name: null,
teamName: null,
bio: null
}
handleChange(dataFromChild) {
console.log(dataFromChild);
}
nextStep(e) {
e.preventDefault();
// Get values via this.refs
var player = {
id: uuid(),
name: ReactDom.findDOMNode(this.refs.name).value,
teamName: ReactDom.findDOMNode(this.refs.teamName).value,
bio: ReactDom.findDOMNode(this.refs.bio).value,
teamId: ReactDom.findDOMNode(this.refs.teamId).value
};
postDataTest(player);
}
render() {
return (
<div className="row">
<div className="col-md-6">
<div className="panel">
<div className="panel-heading">
<h1>Add Player</h1>
</div>
<div className="panel-body">
<form className="form-horizontal">
<div className="form-group">
<label className="control-label">Name</label>
<input type="text" className="form-control" ref="name" defaultValue={this.fieldValues.name}/>
</div>
<div className="form-group">
<label className="control-label">Team Name</label>
<input type="text" className="form-control" ref="teamName" defaultValue={this.fieldValues.teamName}/>
</div>
<TeamSelectBox state={this.state.teamId} onChange={this.handleChange}/>
<div className="form-group">
<label className="control-label">Bio</label>
<input type="textarea" className="form-control" ref="bio" defaultValue={this.fieldValues.bio}/>
</div>
<div className="bs-component">
<button className="btn btn-md btn-default btn-block" onClick={this.nextStep}>Save & Continue</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
module.exports = PlayerForm;
And here is my child form select box
import React, {Component} from "react";
import axios from "axios";
import {postDataTest} from '../actions/postData';
class TeamSelectBox extends Component {
constructor(props) {
super(props);
this.state = {
teams: []
};
}
componentDidMount() {
axios.get("/api/teams")
.then(response => {
const teams = response.data;
this.setState({teams});
console.log(teams);
});
}
render() {
return (
<div className="form-group">
<label for="inputSelect" className="control-label">Select Team</label>
<div className="bs-component">
<select value={this.probs.state.teamId} onChange={this.probs.onChange} className="form-control">
<option value=""></option>
{this.state.teams.map(singleTeam =>
<option value={singleTeam.id}>{singleTeam.team.name}</option>
)}
</select>
</div>
</div>
);
}
}
export default TeamSelectBox;
Your approach seems OK, but you had a typo in your child Component:
{this.probs.onChange}
change it to {this.props.onChange} and try again!
i think you have a typo, you missed spell props, this.props not this.probs
I am pretty new to react/redux I am pretty confused with this simple form.My error state is always undefined eventhough I am getting the error data from node js server Without error data I can't set my state.
routes/users.js
import express from 'express';
import Validator from 'validator';
import isEmpty from 'lodash/isEmpty'
let router = express.Router();
function ValidateInput(data) {
let errors = {};
if(isEmpty(data.email)){
errors.email = 'This fiels is required'
}
if(!Validator.isEmail(data.email)){
errors.email = "Email is in Valid"
}
if(isEmpty(data.password)){
errors.password = 'This fiels is required'
}
if(isEmpty(data.passwordConfirmation)){
errors.passwordConfirmation = 'This fiels is required'
}
if(!Validator.equals(data.password,data.passwordConfirmation)){
errors.passwordConfirmation = "Password Must Macthc"
}
if(isEmpty(data.timezone)){
errors.timezone = 'This fiels is required'
}
return{
errors,
isValid:isEmpty(errors)
}
}
router.post('/',(req,res) => {
console.log(req)
const {errors,isValid} = ValidateInput(req.body);
if(!isValid){
res.status(400).json(errors)
}
});
export default router
SignupForm.js
import React from 'react';
import timezones from '../../data/timezone';
import map from 'lodash/map';
class SignupForm extends React.Component {
constructor(props){
super(props);
this.state = {
username:'',
email:'',
password:'',
passwordConfirmation:'',
timezone:'',
errors:{}
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this)
}
onChange(e){
this.setState({ [e.target.name]:e.target.value })
}
onSubmit(e){
e.preventDefault();
this.setState({ errors:{} });
this.props.userSignupRequest(this.state).then(function (data) {
console.log(data)//Nothing
// this.setState({
// errors:data
// })
})
}
render(){
console.log(this.state)
const options = map(timezones,(val,key) =>
<option key={val} value={val}>{key}</option>
);
return(
<form onSubmit={this.onSubmit}>
<h1>Join our community</h1>
<div className="form-group">
<label className="control-label">Username</label>
<input
type="text"
name="username"
className="form-control"
value={this.state.username}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label className="control-label">Email</label>
<input
type="text"
name="email"
className="form-control"
value={this.state.email}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label className="control-label">Password</label>
<input
type="password"
name="password"
className="form-control"
value={this.state.password}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label className="control-label">passwordConfirmation</label>
<input
type="password"
name="passwordConfirmation"
className="form-control"
value={this.state.passwordConfirmation}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label className="control-label">Time Zone</label>
<select
className="form-control"
name="timezone"
onChange={this.onChange}
value={this.state.timezone}
>
<option value="" disabled>Choose Your Timezone</option>
{options}
</select>
</div>
<div className="form-group">
<button className="btn btn-primary btn-lg">
SignUp
</button>
</div>
</form>
)
}
}
SignupForm.propTypes ={
userSignupRequest:React.PropTypes.func.isRequired
};
export default SignupForm
You need to use catch... so
onSubmit(e){
e.preventDefault();
this.setState({ errors:{} });
this.props.userSignupRequest(this.state)
.then(function (data) {
//Success here
})
.catch(({response}) => console.log(response.data)) //Here you get your errors
})
}