BAD_USER_INPUT Error on Edit value on form user - javascript

Problem
I'm currently working on reactjs + apollo client projects. I'm developing edit user feature. for querying user by username, it works.
but when i'm change the data information. it throws error like this.
Also , i'm getting this error.
Code
Mutation
mutation($username: String!, $input: EditUser!) {
updateUser(username: $username, input: $input) {
full_name
email
group_id
phone
address
}
}
ModalEdit.js
import React, { useEffect, useState } from "react";
import { useQuery, useMutation } from "#apollo/client";
import { Button, Modal, Form } from "react-bootstrap";
import { GET_USER_BY_ID } from "../../../gql/query";
import { UPDATE_USER } from "../../../gql/mutation";
const ModalEdit = (props) => {
// state for check input component
const [isChecked, setIsChecked] = useState("ACTIVE");
// state for input values
const [value, setValue] = useState({
group_id: "",
full_name: "",
email: "",
phone: "",
address: "",
password: "",
});
useEffect(() => {
if (props.show) {
document.body.classList.add("modal-open");
}
return () => {
if (document.body.classList.contains("modal-open")) {
document.body.classList.remove("modal-open");
}
};
}, [props.show]);
const { data, loading, error } = useQuery(GET_USER_BY_ID, {
variables: { username: props.username },
});
const [updateUser, { error: updateError, loading: updateLoading, refetch }] =
useMutation(UPDATE_USER, {
onCompleted: (data) => {
refetch();
},
onError: (err) => {
console.error(JSON.stringify(err, null, 2));
},
});
const dataUser = data?.getUserByID;
useEffect(() => {
if (dataUser) {
setValue({
group_id: dataUser.group_id,
full_name: dataUser.full_name,
email: dataUser.email,
phone: dataUser.phone,
address: dataUser.address,
password: dataUser.password,
});
}
}, [dataUser]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
const handleChange = (event) => {
const { name, value } = event.target;
setValue({ ...value, [name]: value });
};
// handle mutation for edit user
const handleSubmit = (event) => {
event.preventDefault();
console.log(value.full_name);
updateUser({
variables: {
username: props.username,
input: {
group_id: value.group_id,
full_name: value.full_name,
email: value.email,
phone: value.phone,
address: value.address,
password: value.password,
},
},
});
};
return (
<Modal show={props.show}>
<Modal.Header>
<Modal.Title>
{" "}
<span>FORMULIR AKUN PENGGUNA</span>{" "}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Role Akun</Form.Label>
<Form.Select
aria-label="pilih user role"
name="group_id"
onChange={handleChange}
>
<option value={value.group_id}>{value.group_id}</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Nama Lengkap</Form.Label>
<Form.Control
type="text"
name="full_name"
value={value.full_name}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
name="email"
value={value.email}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Phone</Form.Label>
<Form.Control
type="text"
name="phone"
value={value.phone}
onChange={handleChange}
/>
</Form.Group>
<Form.Label>Aktifkan Akun</Form.Label>
{dataUser.status === "ACTIVE" ? (
<Form.Check
type="switch"
checked={isChecked}
onChange={(event) => setIsChecked(event.target.checked)}
id="custom-switch"
label="Aktifkan Akun"
/>
) : (
<Form.Check
type="switch"
id="custom-switch"
checked={isChecked}
onChange={(event) => setIsChecked(event.target.checked)}
label="Aktifkan Akun"
/>
)}
<Button variant="primary" type="submit">
Submit
</Button>
<Button variant="secondary" onClick={props.onClose}>
Close
</Button>
</Form>
</Modal.Body>
</Modal>
);
};
export default ModalEdit;
Question
How to fix BAD_USER_INPUT request?
How to check if email is controlled/uncontrolled components?
any help will be appreciated, thank you

It looks like the input type needs a full_name field as well. I think your problem lies with:
// state for input values
const [value, setValue] = useState({
group_id: "",
full_name: "",
email: "",
phone: "",
address: "",
password: "",
});
...
const handleChange = (event) => {
const { name, value } = event.target;
setValue({ ...value, [name]: value });
};
Because in the context of this function value is == event.target.value and not the value you defined in your setState:
Therefore setValue({...value, [name]: value}); will completely override the state.
Try aliasing the target's value:
const handleChange = (event) => {
const { name, value:tValue } = event.target;
setValue({ ...value, [name]: tValue });
};
I suspect this is a consequence of value.email suddenly becoming undefined based on (1).

Related

React TextField selector complains about of out of range values when updating other TextField components

My intention is to create a simple form CreateUser component where the user input values (username, password, email, role) which are taken from <TextField/> and stored using the useRef hook returning a mutable object.
One of the <TextField/> components is a selector which has the range {ADMIN, PATIENT} and succesfully does it job by changing between these two defined options.
The issue is that whenever I input something, in any of the the TextField components, it results in this message:
Consider providing a value that matches one of the available options or ''.
The available values are `ADMIN`, `PATIENT`.
Although this "does what I intend to do", I trust that this is not well implemented. Please see code below:
import React, { Component, useState, useRef } from "react";
import { Box, Stack, TextField, Typography, MenuItem, Button } from '#mui/material';
const CreateUser = () => {
//Input references
const usernameRef = useRef(null);
const passwordRef = useRef(null);
const emailRef = useRef(null);
const roleRef = useRef(null);
//States
const [user, setUser] = useState({
username: '',
password: '',
email: '',
role: ''
})
const userRoles = [
{
value: 'ADMIN',
label: 'ADMIN'
},
{
value: 'PATIENT',
label: 'PATIENT'
}
]
//Button click function
const handleClick = (event) => {
event.preventDefault();
setUser({
username: usernameRef.current.value,
password: passwordRef.current.value,
email: emailRef.current.value,
role: roleRef.current.value
})
console.log(user)
}
const handleChange = (event, object) => {
setUser({
username: usernameRef.current.value,
password: passwordRef.current.value,
email: emailRef.current.value,
role: event.target.value
})
}
//TODO: Add validation
//BUG: Select should change to current Select state
return (
<Box
component="form"
sx={{
'& .MuiTextField-root': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off">
<h2>Crear Usuario</h2>
<TextField
required
inputRef={usernameRef}
id="message"
name="message"
type="text"
label="Username"
onChange={handleChange}
/><br></br>
<TextField
required
inputRef={passwordRef}
id="message"
name="message"
type="text"
label="Password"
onChange={handleChange}
/><br></br>
<TextField
required
inputRef={emailRef}
id="message"
name="message"
type="text"
label="Email"
onChange={handleChange}
/><br></br>
<TextField
required
inputRef={roleRef}
id="select-role"
select
label="Select Role"
value={user.role}
onChange={handleChange}
helperText="Please select the user role">
{userRoles.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
<Button
onClick={handleClick}>Registrar usuario</Button>
</Box>
)
}
export default CreateUser;

React - using nested objects as state with hooks to fill form data

I have a nested object as state like below -
const [userInfo, setUserInfo] = useState({
author:"",
user: {
name: 'rahul',
email: 'rahul#gmail.com',
phone: [{ primary: '8888888810' }, { alternate: '7777777716' }]
}
});
I want to have 5 input fields - author, name, email, primary, and alternate and want to use only one handleChange() method to change the fields.
You can find the code I wrote on the link - https://stackblitz.com/edit/react-ngpx7q
Here, I am not able to figure out how to update the state correctly. Any help would be greatly appreciated.
Since this was an interview question then I'd avoid 3rd-party libraries. You can use a switch statement to handle the differently nested state, namely the name and email in the second level and primary and alternate in the third level.
const handleChange = (e) => {
const { name, value } = e.target;
switch (name) {
case "name":
case "email":
setUserInfo((userInfo) => ({
user: {
...userInfo.user,
[name]: value
}
}));
break;
case "primary":
case "alternate":
setUserInfo((userInfo) => ({
user: {
...userInfo.user,
phone: userInfo.user.phone.map((el) =>
el.hasOwnProperty(name)
? {
[name]: value
}
: el
)
}
}));
break;
default:
// ignore
}
};
Demo
you can use lodash set to assign the value for the deeply nested object. You need to pass the path to the name prop of your input .
import set from 'lodash/set'
const App = () => {
const [userInfo, setUserInfo] = useState({
author:"",
user: {
name: 'rahul',
email: 'rahul#gmail.com',
phone: [{ primary: '8888888810' }, { alternate: '7777777716' }]
}
});
const handleChange = (e) => {
// clone the state
const userInfoCopy = JSON.parse(JSON.stringify(userInfo));
set(userInfoCopy, e.target.name, e.target.value)
setUserInfo(userInfoCopy)
}
console.log(userInfo)
return (
<div>
<input
name="user.name"
onChange={handleChange}
/>
<input
name="user.phone.[0].primary"
onChange={handleChange}
/>
</div>
);
};
Now you can use a single handleChange method for updating all your keys in the state .
Instead of treating phone as object of array, which i don't think is a good idea, treat it as single object with primary and alternate as key value pairs
import React, { useState } from 'react';
import './style.css';
export default function App() {
const [userInfo, setUserInfo] = useState({
user: {
name: 'ravi',
email: 'ravi#gmail.com',
phone: {
primary: 345345345345,
alternate: 234234234234
}
}
});
const handleChange = e => {
console.log(e.target.name);
setUserInfo(prevState => {
return {
user: {
...prevState.user,
[e.target.name]: e.target.value,
phone: {
...prevState.user.phone,
...{ [e.target.name]: e.target.value }
}
}
};
});
};
const {
name,
email,
phone: { primary, alternate }
} = userInfo.user;
console.log(userInfo);
return (
<div className="App">
Name: <input name="name" value={name} onChange={e => handleChange(e)} />
<br />
Email:{' '}
<input name="email" value={email} onChange={e => handleChange(e)} />
<br />
Primary:{' '}
<input name="primary" value={primary} onChange={e => handleChange(e)} />
<br />
Alternate:{' '}
<input
name="alternate"
value={alternate}
onChange={e => handleChange(e)}
/>
<br />
</div>
);
}
This works based on your original data (where phone is an array of objects):
const handleChange = e => {
let name = e.target.name;
if (['name', 'email'].includes(name)) {
setUserInfo(prevState => {
return {
user: {
...prevState.user,
[name]: e.target.value,
}
};
});
} else {
setUserInfo(prevState => {
return {
user: {
...prevState.user,
phone: name === 'primary' ?
[prevState.user.phone.find(e => Object.keys(e).includes('alternate')), {[name]: e.target.value}] :
[prevState.user.phone.find(e => Object.keys(e).includes('primary')), {[name]: e.target.value}]
}
};
});
}
};
I copy paste your code and only edit your handleChange
import React, { useState } from 'react';
import './style.css';
export default function App() {
const [userInfo, setUserInfo] = useState({
user: {
name: 'ravi',
email: 'ravi#gmail.com',
phone: [{ primary: '9999999990' }, { alternate: '9999998880' }]
}
});
const handleChange = e => {
console.log(e.target.name);
let arrPhone = userInfo.user.phone;
(e.target.name == 'primary' || e.target.name == 'alternate' )
&& arrPhone.map(x => (x.hasOwnProperty(e.target.name)) && (x[e.target.name] = e.target.value))
console.log(arrPhone)
setUserInfo(prevState => {
return {
user: {
...prevState.user,
[e.target.name]: e.target.value,
phone: arrPhone
}
};
});
};
const {
name,
email,
phone: [{ primary }, { alternate }]
} = userInfo.user;
console.log(userInfo);
return (
<div className="App">
Name: <input name="name" value={name} onChange={handleChange} />
<br />
Email: <input name="email" value={email} onChange={handleChange} />
<br />
Primary: <input name="primary" value={primary} onChange={handleChange} />
<br />
Alternate:{' '}
<input name="alternate" value={alternate} onChange={handleChange} />
<br />
</div>
);
}

useState() hook not updating the value on change

Little context, I am trying to create a form for for getting User Signup.
I first wrote code as following .
import { useState } from 'react';
const SignupComponent = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
error: '',
loading: false,
message: '',
showForm: true
})
const { name, email, password, error, loading, showForm } = formData;
const onChange = e => {
setFormData({ ...formData, error: false, [e.target.name]: e.target.value })
console.log(name)
}
const handleSubmit = async e => {
e.preventDefault();
console.table({ name, email, password, error, loading, showForm })
}
const signupForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input type="text" className="form-control" placeholder="Enter Your Name" values={name} onChange={e => onChange(e)} />
</div>
<div className="form-group">
<input values={email} onChange={e => onChange(e)} type="email" className="form-control" placeholder="Enter Your Email" />
</div>
<div className="form-group">
<input values={password} onChange={e => onChange(e)} type="password" className="form-control" placeholder="Enter Your Password" />
</div>
<div>
<button className="btn btn-primary">Signup</button>
</div>
</form>
);
};
return <React.Fragment>{signupForm()}</React.Fragment>};
export default SignupComponent;
I noticed that in this code snippet, the state in setFormData is not getting updated, console logging name or any other value returns a empty string.
result for the above code
But after tweaking the code as such
import { useState } from 'react';
const SignupComponent = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
error: '',
loading: false,
message: '',
showForm: true
})
const { name, email, password, error, loading, showForm } = formData;
const handleChange = value => (e) => {
setFormData({ ...formData, error: false, [value]: e.target.value })
console.log(name)
}
const handleSubmit = async e => {
e.preventDefault();
console.table({ name, email, password, error, loading, showForm })
}
const signupForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input type="text" className="form-control" placeholder="Enter Your Name" values={name} onChange={handleChange('name')} />
</div>
<div className="form-group">
<input values={email} onChange={handleChange('email')} type="email" className="form-control" placeholder="Enter Your Email" />
</div>
<div className="form-group">
<input values={password} onChange={handleChange('password')} type="password" className="form-control" placeholder="Enter Your Password" />
</div>
<div>
<button className="btn btn-primary">Signup</button>
</div>
</form>
);
};
return <React.Fragment>{signupForm()}</React.Fragment> };
export default SignupComponent;
Makes the code work and result is as desired. As in this image.
2nd way
Why is this behaving like this. Why is the first way not working.
You forgot the name attribute in your inputs, and the value attribute without s
<input name="email" value={email} onChange={onChange} ... />
then
const onChange = e => {
// The event will get passed as an argument even if you don't bind it in onChange={onChange}.
console.log(e.target.name, e.target.value)
setFormData({ ...formData, error: false, [e.target.name]: e.target.value })
}
The event will get passed as an argument.
It works for the second cause you're passing the name as an argument
see docs, https://reactjs.org/docs/thinking-in-react.html
React’s one-way data flow (also called one-way binding) keeps everything modular and fast.
Important thing to solve your question.
The Functional Component(FC) state is changed, UI is re-rendered.
But, your signupForm render function is declared in FC.
So, It is re-delcared as a new, when SignupComponent state is changed.
First. change signupForm render function to FC component.
Second, Pass props to component.
Thrid, re-used them.
import React from 'react'; // React is required to render JSX
const FormInput = ({
type,
placeholder,
value,
onChange,
}) => (
<div className="form-group">
<input type={type} className="form-control" placeholder={placeholder} value={value} onChange={onChange} />
</div>
);
const SignupComponent = () => {
const [formData, setFormData] = React.useState({
name: '',
email: '',
password: '',
error: false,
loading: false,
message: '',
showForm: true,
});
const {
name, email, password, error, loading, showForm,
} = formData;
const handleChange = (value) => (e) => {
setFormData({
...formData,
error: false,
[value]: e.target.value,
});
console.log(name);
};
const handleSubmit = async (e) => {
e.preventDefault();
console.table({
name, email, password, error, loading, showForm,
});
};
return (
<form onSubmit={handleSubmit}>
<FormInput type="text" value={name} placeholder="Enter Your Name" onChange={handleChange('name')} />
<div>
<button type="submit" className="btn btn-primary">Signup</button>
</div>
</form>
);
};
export default SignupComponent;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

value is not shown in the field when using redux form

I am using redux-form for the form. The form gets submitted but if page is refreshed
I need to show that submitted data which comes from the server. Everything is working,
the local state is also updated from getDerivedStateFromProps but the field does not
show with the data. I used plain input tag and it shows up the data. What have i missed?
Here is what I have done
UPDATE
const mapStateToProps = (state) => {
const { company } = state.profile.companyReducer;
return {
getCompany: state.profile.companyReducer,
initialValues: company && company.records,
};
};
const mapDispatchToProps = dispatch => ({
loadCompany: () => dispatch(loadCompany()),
saveCompany: companyData => dispatch(saveCompany(companyData)),
});
const withConnect = connect(
mapStateToProps,
mapDispatchToProps,
);
const withReduxForm = reduxForm({
form: 'companyForm',
fields: requiredFields,
validate,
// initialValues: {
// company_name: 'company',
// },
destroyOnUnmount: false,
enableReinitialize: true,
keepDirtyOnReinitialize: true,
});
const initialState = {
company_name: 'hello',
website: '',
industry: '',
number_of_employees: '',
phone_number: '',
founded: '',
address: '',
city: '',
state: '',
zip_code: '',
country: '',
wiki: '',
headquarter: '',
speciality: '',
type: '',
};
const enhance = compose(
withReduxForm,
withConnect,
withState('company', 'updateCompany', initialState),
withHandlers({
handleChange: props => ({ target: { name, value } }) => {
props.updateCompany({ ...props.company, [name]: value });
},
handleSubmit: props => (event) => {
event.preventDefault();
props.saveCompany(props.company);
},
}),
setStatic('getDerivedStateFromProps', (nextProps) => {
const { company } = nextProps.getCompany;
if (company && company.records !== undefined) {
console.log('company records getDerivedStateFromProps', company.records);
return {
company: company.records,
};
}
return null;
}),
lifecycle({
componentDidMount() {
this.props.loadCompany();
},
}),
);
export default enhance;
const Company = ({
company,
handleChange,
handleSubmit,
}: {
company: Object,
handleChange: Function,
handleSubmit: Function
}) => {
console.log('company', company);
return (
<React.Fragment>
<FormHeadline headline="Company" weight="400" />
<Wrapper>
<GridContainer container spacing={24}>
<StyledForm autoComplete="off" onSubmit={handleSubmit}>
<FormWrapper>
<input
name="company_name"
id="company_name"
type="text"
label="Company Name"
className="input-field"
value={company.company_name}
onChange={handleChange}
/>
{/* <Field
id="company_name"
name="company_name"
type="text"
label="Company Name"
className="input-field"
value="Hello"
onChange={handleChange}
component={GTextField}
required
margin="normal"
/> */}
<Field
id="website"
name="website"
type="text"
label="Website"
placeholder="Website"
className="input-field"
value={company.website}
onChange={handleChange}
component={GTextField}
required
margin="normal"
/>
</FormWrapper>
</StyledForm>
</GridContainer>
</Wrapper>
</React.Fragment>
);
};
export default enhance(Company);
generic text field
const GTextField = ({
input,
label,
meta: { touched, error },
...rest
}: {
input: any,
label: Node,
meta: {
touched: boolean,
error: boolean
}
}) => {
console.log('rest', input);
return (
<TextField
label={label}
helperText={touched && error}
error={!!(touched && error)}
{...input}
{...rest}
/>
);
};
This works but not the Field one
<input
name="company_name"
id="company_name"
type="text"
label="Company Name"
className="input-field"
value={company.company_name}
onChange={handleChange}
/>
UPDATE
props.initialValues shows the following but still the field is not updated
here is the full code
https://gist.github.com/MilanRgm/e3e0592c72a70a4e35b72bb6107856bc
Hi first replace the input tag with the commented out field component itself then set these flags in reduxform
const withReduxForm = reduxForm({
form: 'companyForm',
fields: requiredFields,
validate,
destroyOnUnmount: false,
enableReinitialize: true,
keepDirtyOnReinitialize: true
});
as well as pass the initialValues props to the form container with the server response
{
company_name: 'response value from server'
}
Hi checkout this fiddle link for initialValues example. For your example with reducer
const mapStateToProps = state => ({
getCompany: state.profile.companyReducer,
initialValues: state.profile.[your reducer object] });

Axios Post Form with Reactjs

So I have this post method with Axios and if I submit this, it said
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
If I use this method:
axios.post('http://localhost:5000/users', ({userid: this.state.userid})
it works. But if I add 2 or more arg to the axios post it gets error again:
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
Here is my full code. As you can see I try different combinations of code, and it only works if I only pass 1 arg.
import React from 'react';
import axios from 'axios';
// import { Form } from 'antd';
// import { List, Card, Form } from 'antd';
export default class FormUser extends React.Component {
// constructor(props) {
// super(props)
// this.state = {
state = {
userid: '',
fullname: '',
usergroup:'',
emailid: '',
mobile: '',
title: '',
};
handleChange = event => {
this.setState({ userid: event.target.value });
this.setState({ fullname: event.target.value });
this.setState({ usergroup: event.target.value });
this.setState({ emailid: event.target.value });
this.setState({ mobile: event.target.value });
this.setState({ title: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
// const userform = {userid: this.state.userid};
// const fullnameForm = {fullname: this.state.fullname};
// const usergroupForm = {usergroup: this.state.usergroup};
// const emailidForm = {emailid: this.state.emailid};
// const mobileForm = {mobile: this.state.mobile};
// const titleForm = {title: this.state.title};
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
// { {userid: this.state.userid}, {fullname: this.state.fullname} , usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title })
// { userform, fullnameForm, usergroupForm, emailidForm, mobileForm, titleForm })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>User Project ID: <input type="text" name="userid" onChange={this.handleChange}/></label><br/>
<label>Full Name: <input type="text" name="fullname" onChange={this.handleChange}/></label><br/>
<label>User Group: <input type="text" name="usergroup" onChange={this.handleChange}/></label><br/>
<label>Email: <input type="text" name="emailid" onChange={this.handleChange}/></label><br/>
<label>Mobile: <input type="text" name="mobile" onChange={this.handleChange}/></label><br/>
<label>Title: <input type="text" name="title" onChange={this.handleChange}/></label>
<button type="submit">Add</button>
</form>
)
}
}
AXIOS POST on Express
app.post('/users', function (req, res) {
var postData = req.body;
// postData.created_at = new Date();
connection.query("INSERT INTO users SET ?", postData, function (error, results, fields) {
if (error) throw error;
console.log(results.insertId);
res.end(JSON.stringify(results));
});
});
eventHandler for each state. Is there any way I can do this better?
yes it would work something like this
import React, { Component } from 'react';
class UserForm extends Component {
constructor() {
super();
this.state = {
fname: '',
lname: '',
email: '',
};
}
onChange = (e) => {
/*
Because we named the inputs to match their
corresponding values in state, it's
super easy to update the state
*/
this.setState({ [e.target.name]: e.target.value });
}
render() {
const { fname, lname, email } = this.state;
return (
<form>
<input
type="text"
name="fname"
value={fname}
onChange={this.onChange}
/>
<input
type="text"
name="lname"
value={lname}
onChange={this.onChange}
/>
<input
type="text"
name="email"
value={email}
onChange={this.onChange}
/>
</form>
);
}
}
and about submission of the form your axios post would work something like this
onSubmit = (e) => {
e.preventDefault();
// get our form data out of state
const { fname, lname, email } = this.state;
axios.post('/', { fname, lname, email })
.then((result) => {
//access the results here....
});
}
axios.post(url[, data[, config]])'s 3rd argument is the Axios configuration object, which you're inadvertently passing in in
axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))
so the request gets misconfigured and doesn't work.
Instead, all of the data to POST should be in the single data object.
axios.post('http://localhost:5000/users', {
userid: this.state.userid,
fullname: this.state.fullname,
})
So apparently I have to add eventhandler for each state. Is there any way I can do this better?
import React from 'react';
import axios from 'axios';
import { Form } from 'antd';
// import { List, Card, Form } from 'antd';
const FormItem = Form.Item;
export default class FormUser extends React.Component {
// constructor(props) {
// super(props)
// this.state = {
state = {
userid: '',
fullname: '',
usergroup: '',
emailid: '',
mobile: '',
title: '',
};
handleUserIDChange = event => {this.setState({ userid: event.target.value })}
handleFullNameChange = event => {this.setState({ fullname: event.target.value })}
handleUserGroupChange = event => {this.setState({ usergroup: event.target.value })}
handleEmailIDChange = event => {this.setState({ emailid: event.target.value })}
handleMobileChange = event => {this.setState({ mobile: event.target.value })}
handleTitleChange = event => {this.setState({ title: event.target.value })}
handleSubmit = event => {
event.preventDefault();
// const userform = {userid: this.state.userid};
// const fullnameForm = {fullname: this.state.fullname};
// const usergroupForm = {usergroup: this.state.usergroup};
// const emailidForm = {emailid: this.state.emailid};
// const mobileForm = {mobile: this.state.mobile};
// const titleForm = {title: this.state.title};
axios.post('http://localhost:5000/users',
{ userid: this.state.userid, fullname: this.state.fullname, usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title },)
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
// const formItemLayout = {
// labelCol: {
// xs: { span: 24 },
// sm: { span: 8 },
// },
// wrapperCol: {
// xs: { span: 24 },
// sm: { span: 16},
// },
// };
<Form onSubmit={this.handleSubmit}>
<FormItem>
<label>User Project ID: <input type="text" name="this.state.userid" onChange={this.handleUserIDChange} /></label>
</FormItem>
<FormItem>
<label>Full Name: <input type="text" name="this.state.fullname" onChange={this.handleFullNameChange} /></label><br />
</FormItem>
<FormItem>
<label>User Group: <input type="text" name="this.state.usergroup" onChange={this.handleUserGroupChange} /></label><br />
</FormItem>
<FormItem>
<label>Email: <input type="text" name="this.state.emailid" onChange={this.handleEmailIDChange} /></label>
</FormItem>
<FormItem>
<label>Mobile: <input type="text" name="this.state.mobile" onChange={this.handleMobileChange} /></label>
</FormItem>
<FormItem>
<label>Title: <input type="text" name="this.state.title" onChange={this.handleTitleChange} /></label>
</FormItem>
<button type="submit">Add</button>
</Form>
)
}
}

Categories

Resources