React Redux action not dispatched but request is successful - javascript

I'm trying to implement authentication on my project, as title says it registers an user but actions are not dispatched. I have almost the same action for fetching data, it works, dispatches the actions. is the function:
export const signIn = data => dispatch => {
dispatch({
type: SIGN_UP
})
fetch(API_URL+'/register', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(message => dispatch({
type: SIGN_UP_SUCCESS, payload: message
}))
.catch(error => dispatch({
type: SIGN_UP_FAILED, payload: error
}))
}
Reducer:
export const authReducer = (state = initialState, action) => {
switch(action.type) {
case SIGN_UP:
return {
...state,
loading: true
}
case SIGN_UP_SUCCESS:
return {
...state,
loading: false,
message: action.payload
}
case SIGN_UP_FAILED:
return {
...state,
loading: false,
error: action.payload
}
default:
return state
}
}
connect method:
export default connect(null, { signIn })(RegisterForm);
Register Form component code(just to satisfy Stackoverflow's wishes):
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Form, Button, Message, Field } from 'semantic-ui-react';
import validator from 'email-validator';
import { signUp } from '../../actions/authActions';
class RegisterForm extends React.Component {
constructor(props) {
super(props)
this.state = {
data: {
username: '',
name: '',
email: '',
password: '',
city: '',
address: ''
},
errors: {}
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = e => {
this.setState({
...this.state,
data: { ...this.state.data, [e.target.name]: e.target.value}
})
}
handleSubmit = e => {
console.log(this.state.data)
e.preventDefault();
const errs = this.validate(this.state.data);
this.setState({
errors: errs
});
if(Object.keys(this.state.errors).length === 0) {
this.props.signUp(this.state.data)
}
}
validate = data => {
const errors = {};
if(!data.username) errors.username = 'Username is required';
if(!data.name) errors.name = 'Name is required';
if(!data.email) errors.email = 'Email is required';
if (!validator.validate(data.email)) errors.email = "Invalid email";
if(!data.password) errors.password = 'Password is required';
if(!data.city) errors.city = 'City is required';
if(!data.address) errors.address = 'Address is required'
return errors
}
render() {
const { errors, data } = this.state
return <Form onSubmit={this.handleSubmit}>
<Form.Field>
<label>Username</label>
<input
placeholder='Username'
name="username"
type="text"
onChange={this.handleChange}
value={this.state.data.username}
/>
</Form.Field>
{errors.username && <Message error header={errors.username}/>}
<Form.Field>
<label>Name</label>
<input
placeholder='Name'
name="name"
type="text"
onChange={this.handleChange}
value={this.state.data.name}
/>
</Form.Field>
{errors.name && <Message error header={errors.name}/>}
<Form.Field>
<label>Address</label>
<input
placeholder='Address'
name="address"
type="text"
onChange={this.handleChange}
value={this.state.data.address}
/>
</Form.Field>
{errors.address && <Message error header={errors.address}/>}
<Form.Field>
<label>City</label>
<input
placeholder='City'
name="city"
type="text"
onChange={this.handleChange}
value={this.state.data.city}
/>
</Form.Field>
{errors.city && <Message error header={errors.city}/>}
<Form.Field>
<label>Email</label>
<input
placeholder='Email'
name="email"
type="email"
onChange={this.handleChange}
value={this.state.data.email}
/>
</Form.Field>
{errors.email && <Message error header={errors.email}/>}
<Form.Field>
<label>Password</label>
<input
placeholder='Password'
name="password"
type="password"
onChange={this.handleChange}
value={this.state.data.password}
/>
</Form.Field>
{errors.password && <Message error header={errors.password}/>}
<Button type='submit'>Register</Button>
</Form>
}
}
export default connect(null, { signUp })(RegisterForm);

Your code seems to be fine, make sure your redux-devtools is implemented correctly.
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(thunk)) // [, rest of middlewares]

Did you use bindActionCreators inside your component? in handleSubmit you just called action without dispatching it

Related

Not able to get response while sending my data to backend in reactjs

I am using axios for sending my data using POST method.
This axios is not giving me response on the console.
Since, I have also used promise but still not able to get the response on console.
Notice: I am getting the data which I sent...flow of control is not entering into then() promise.
import "./SignUp.css";
import React, { Component } from "react";
import "../SignIn/SignIn.css";
import Organization from "../../Organization/organization";
import axios from "axios";
import { withRouter } from "react-router";
export class SignUp extends Component {
constructor() {
super();
this.state = {
firstName: "",
lastName: "",
password: "",
email: "",
organizationName: "",
};
this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
this.handleLastNameChange = this.handleLastNameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleOrganizationNameChange = this.handleOrganizationNameChange.bind(
this
);
this.handleSubmitLogin = this.handleSubmitLogin.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
}
handleFirstNameChange(event) {
this.setState({ firstName: event.target.value });
}
handleLastNameChange(event) {
this.setState({ lastName: event.target.value });
}
handleOrganizationNameChange(event) {
this.setState({ organizationName: event.target.value });
}
handlePasswordChange(event) {
this.setState({ password: event.target.value });
}
handleEmailChange(event) {
this.setState({ email: event.target.value });
}
async handleSubmitLogin() {
var organizationRecord = new Organization(
this.state.firstName,
this.state.lastName,
this.state.password,
this.state.email,
this.state.organizationName
);
const data = {
First_Name: organizationRecord.getFirstName,
Last_Name: organizationRecord.getLastName,
Password: organizationRecord.getPassword,
Email: organizationRecord.getEmail,
Organization_Name: organizationRecord.getOrganizationName,
};
// Code Starts here
try {
axios
.post("http://localhost:8000/Organization", data)
.then((result) => {
console.log(`Status Code: ${result.status}`);
})
.catch((err) => {
console.error(err);
});
sessionStorage.clear();
sessionStorage.setItem(
"email",
JSON.stringify(organizationRecord.getEmail)
);
this.props.history.push("/sign-in/redirect");
} catch (error) {
console.error(error);
}
//Code ends here
}
render() {
return (
<div className="sign-up-container">
<div className="sign-in-input">
<h2>SIGN UP</h2>
<div className="sign-in-input-inner">
<input
className="input"
value={this.state.firstName}
onChange={this.handleFirstNameChange}
type="text"
placeholder="First Name"
/>
<input
className="input"
type="text"
value={this.state.lastName}
onChange={this.handleLastNameChange}
placeholder="Last Name"
/>
<input
className="input"
type="email"
value={this.state.email}
onChange={this.handleEmailChange}
placeholder="Email"
/>
<input
className="input"
type="text"
value={this.state.organizationName}
onChange={this.handleOrganizationNameChange}
placeholder="Organization Name"
/>
<input
className="input"
type="password"
value={this.state.password}
onChange={this.handlePasswordChange}
placeholder="Password"
/>
<div
onClick={this.handleSubmitLogin}
className="sign-in-button-container sign-up-button-container"
>
Submit
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(SignUp);
Can anyone explain me where I am lagging?

Parent Component losing state immediately after re render Reactjs

I'm very new to React and I'm trying to write an app that will automatically display a Login page on startup, and when the user successfully logs in the parent component updates its state to render the Dashboard component instead of Login.
What I am finding is that when the user logs in, it updates the parent components state correctly and displays the Dashboard component for a second but then its state changes again and re-renders the Login component. I think something is causing the state to reset, but I'm not sure what.
User.js:
class User extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
isLoggedIn: false
}
this.updateUser = this.updateUser.bind(this);
}
updateUser(newEmail) {
console.log(`Entered User.updateUser, email: ${newEmail}`);
this.setState({
email: newEmail,
isLoggedIn: false
});
}
render() {
if (this.state.isLoggedIn) {
return <Dashboard/>
}
return <Login updateTheUser={this.updateUser}/>
}
}
export default User;
Login.js:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleResponse = this.handleResponse.bind(this);
}
handleEmailChange(event) {
this.setState({email: event.target.value})
}
handlePasswordChange(event) {
this.setState({password: event.target.value})
}
handleResponse(res) {
if (res.ok) {
alert('Login Successful!');
this.props.updateTheUser(this.state.email);
}
else if (res.status === 401) {
alert('Wrong Username or Password');
}
}
async sendLoginRequest(data) {
await fetch('http://localhost:8000/login/', {
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: data,
})
.then(this.handleResponse)
.catch(function(error) {
alert('Server error, please try again.');
console.error(error);
});
}
handleSubmit(event) {
const data = `{"email": "${this.state.email}", "password": "${this.state.password}"}`
this.sendLoginRequest(data);
}
render () {
return (
<div id="container" className="col-md-12" align="center">
<div id="vertical-center-div"className="col-sm-4 card bg-light">
<Form onSubmit={this.handleSubmit}>
<Form.Label className="display-4 text-secondary">Login</Form.Label>
<Form.Group controlId="formBasicEmail">
<Form.Control type="email" value={this.state.email} onChange={this.handleEmailChange} placeholder="Email" required/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Control type="password" value={this.state.password} onChange={this.handlePasswordChange} placeholder="Password" required/>
</Form.Group>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Remember me" />
</Form.Group>
<Button id="submitButton" variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
)
}
}
export default Login;
Dashboard.js:
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
expenses: [],
incomings: []
}
}
render () {
return (
<>
<p className="display-4">Dashboard</p>
</>
)
}
}
export default Dashboard;
It seems, that in Login.js you need to prevent default submit behaviour with event.preventDefault()
handleSubmit(event) {
event.preventDefault()
const data = `{"email": "${this.state.email}", "password": "${this.state.password}"}`
this.sendLoginRequest(data);
}

Redirect (react-router-dom) is not working in react class component

I am trying to redirect to a specific route after the successful registration of the user
but Redirect is not working.
I do land inside the condition in componentDidMount just before render,
where it needs to redirect to that route but it doesn't
I want to return that in the componentDidMount function
How can I get through this situation?
import { Alert, Button, Form, FormGroup, Label, Input, Container, FormFeedback } from 'reactstrap';
import { connect } from 'react-redux';
import { register } from '../../actions/authActions'
import { Redirect } from 'react-router-dom'
// import PropTypes from 'prop-types'
class Register extends Component {
state = {
firstname: '',
lastname: '',
email: '',
password: '',
confirmPassword: '',
role: '',
firstnameError: null,
lastnameError: null,
emailError: null,
passwordError: null,
confirmPasswordError: null,
roleError: null,
msg: null,
}
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
};
validate = () => {
let isError = false;
const { firstname, lastname, email, password, confirmPassword, role } = this.state;
if (firstname === '') {
this.setState({
firstnameError: "First Name is Required"
});
isError = true
}
if (lastname === '') {
this.setState({
lastnameError: "Last Name is Required"
});
isError = true
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) {
this.setState({
emailError: "Enter Correct Email Format"
});
isError = true
}
if (email === '') {
this.setState({
emailError: "Email is Required"
});
isError = true
}
if (password === '') {
this.setState({
passwordError: "Password is Required"
});
isError = true
}
if (password.length < 6) {
this.setState({
passwordError: "Password length should be greater than 6 characters"
});
isError = true
}
if (password !== confirmPassword) {
this.setState({
confirmPasswordError: "Confirm Password should match the Password"
});
isError = true
}
if (confirmPassword.length < 6) {
this.setState({
passwordError: "Confirm Password length should be greater than 6 characters"
});
isError = true
}
if (role === '') {
this.setState({
roleError: "Select a role"
});
isError = true
}
return isError
}
onSubmit = (e) => {
e.preventDefault();
this.setState({
firstnameError: null,
lastnameError: null,
emailError: null,
passwordError: null,
confirmPasswordError: null,
roleError: null
})
const isError = this.validate();
if (!isError) {
const { firstname, lastname, email, password, role, error } = this.state;
const newUser = {
firstname,
lastname,
email,
password,
role
};
this.props.register(newUser);
console.log(newUser)
}
};
componentDidUpdate(prevProps) {
const { error } = this.props;
console.log("outside");
if (error != prevProps.error) {
console.log("inside");
if (error.id === 'REGISTER_FAIL') {
this.setState({ msg: this.props.error.msg })
console.log("inside error");
}
else if (error.id === null) {
this.setState({ msg: null })
console.log("inside login");
return (<Redirect to="/some" />);
}
}
}
render() {
return (
<Container className="mt-5">
{this.state.msg ? <Alert color="danger">{this.state.msg}</Alert> : null}
<Form onSubmit={this.onSubmit}>
<FormGroup>
<Label for="firstname">First Name</Label>
<Input onChange={this.onChange} type="firstname" name="firstname" id="firstname" placeholder="First Name"
invalid={this.state.firstnameError !== null}
valid={this.state.firstnameError == null && this.state.firstname.length > 0} />
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.firstnameError}</FormFeedback>
</FormGroup>
<FormGroup>
<Label for="lastname">Last Name</Label>
<Input onChange={this.onChange} type="lastname" name="lastname" id="lastname" placeholder="Last Name"
invalid={this.state.lastnameError !== null}
valid={this.state.lastnameError == null && this.state.lastname.length > 0} />
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.lastnameError}</FormFeedback>
</FormGroup>
<FormGroup>
<Label for="email"> Email </Label>
<Input onChange={this.onChange} type="email" name="email" id="email" placeholder="Email"
invalid={this.state.emailError !== null}
valid={this.state.emailError == null && (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.state.email))} />
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.emailError}</FormFeedback>
</FormGroup>
<FormGroup>
<Label for="password">Password</Label>
<Input onChange={this.onChange} type="password" name="password" id="password" placeholder="Password"
invalid={this.state.passwordError != null}
valid={this.state.passwordError == null && this.state.password.length > 6} />
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.passwordError}</FormFeedback>
</FormGroup>
<FormGroup>
<Label for="confirmPassword">Confirm Password</Label>
<Input onChange={this.onChange} type="password" name="confirmPassword" id="confirmPassword" placeholder="Confirm Password"
invalid={this.state.confirmPasswordError != null}
valid={this.state.confirmPasswordError == null && this.state.confirmPassword.length > 6} />
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.confirmPasswordError}</FormFeedback>
</FormGroup>
<FormGroup>
<Label for="role">Role</Label>
<Input onChange={this.onChange} type="select" name="role" id="role"
invalid={this.state.roleError != null}
valid={this.state.roleError == null && this.state.role.length > 0}>
<option value='' >Select from below roles</option>
<option value="student">Student</option>
<option value="Instructor">Professor / Instructor</option>
<option value="Professional">Industry Professional</option>
</Input>
<FormFeedback valid="true">Alright</FormFeedback>
<FormFeedback invalid="true">{this.state.roleError}</FormFeedback>
</FormGroup>
<Button>Submit</Button>
</Form>
</Container>
);
}
}
const mapStateToProps = state => ({
error: state.error,
user: state.auth.user
})
export default connect(mapStateToProps, { register })(Register)
You can't render JSX from any lifecycle component other than render. You can, however, return a Redirect in the render function or use the history route prop to push new routes or replace the current route. For the history prop your component Register would need to either be directly rendered by a Route's render, component, or children prop or the withRouter HOC.
Render Redirect
componentDidUpdate(prevProps) {
const { error } = this.props;
console.log("outside");
if (error != prevProps.error) {
console.log("inside");
if (error.id === 'REGISTER_FAIL') {
this.setState({ msg: this.props.error.msg })
console.log("inside error");
} else if (error.id === null) {
this.setState({ msg: null, redirect: true })
}
}
}
...
render() {
if (this.state.redirect) {
return <Redirect to="/some" />;
}
...
Programmatically Replace Route
Here's an example with withRouter decorator:
First, decorate your exported Register component
import { withRouter } from 'react-router-dom';
export default withRouter(
connect(mapStateToProps, { register })(Register),
);
or
import { compose } from 'redux';
import { withRouter } from 'react-router-dom';
export default compose(
withRouter,
connect(mapStateToProps, { register }),
)(Register);
Second (or if Register already has route-props), use the now added history prop:
componentDidUpdate(prevProps) {
const { error } = this.props;
console.log("outside");
if (error != prevProps.error) {
console.log("inside");
if (error.id === 'REGISTER_FAIL') {
this.setState({ msg: this.props.error.msg })
console.log("inside error");
} else if (error.id === null) {
this.setState({ msg: null })
console.log("inside login");
this.props.history.replace("/some");
}
}
}
I think you meant the componentDidUpdate function. I don't see a componentDidMount function here at all.
Why don't you just use:
this.props.history.push({pathname: '/some'});

Cannot Get ReactJS Component to Update

I'm attempting to update an area on my page once a fetch() call has been made with the resulting error message from the fetch() call. The fetch() call is executed when the form button is submitted.
When fetch() has completed, I have written ErrorMessage(data['Result']); which I thought would pass data['Result'] as the props. You can see in my render that I have <ErrorMessage error="Original Message" /> which is what I thought would update with the message from the fetch() call.
Please see my full code below for this page:
import React from 'react';
import './css/LoginForm.css';
function ErrorMessage(props) {
return (
<p id="error-message">
{props.error}
</p>
)
}
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
var loginData = {
username: this.state.username,
password: this.state.password
}
fetch('/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginData: loginData
})
})
.then(function(response) {
return response.json();
})
.then(function(data) {
if (data['Result']) {
console.log(data['Result']);
ErrorMessage(data['Result']);
}
})
.catch(function(error) {
console.log('Error: ', error);
});
}
render() {
return (
<div id="login-form-container">
<form id="login-form" onSubmit={this.handleSubmit} method="POST">
<ErrorMessage error="Original Message" />
<input
type="text"
name="username"
placeholder="username"
autoComplete="username"
onFocus={(e) => e.target.placeholder = ''}
onBlur={(e) => e.target.placeholder = 'username'}
value={this.state.username}
onChange={this.handleInputChange}
required
></input>
<input
type="password"
name="password"
placeholder="password"
autoComplete="current-password"
onFocus={(e) => e.target.placeholder = ''}
onBlur={(e) => e.target.placeholder = 'password'}
value={this.state.password}
onChange={this.handleInputChange}
required
></input>
<button type="submit" name="submit">Login</button>
<p className="forgotten-password">Forgotten your password?</p>
</form>
</div>
);
}
}
export default LoginForm;
This may be completely wrong as I am struggling to understand exactly how a component works in ReactJS, so I apologise in advance. Thank you for any insight.
Creating a component when your fetch is complete will not affect what is returned from the render method of your LoginForm component.
You could instead set the error message in the LoginForm state, and use that as props for the ErrorMessage component in the render method.
Example
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
error: "Original Message"
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// ...
handleSubmit(event) {
event.preventDefault();
var loginData = {
username: this.state.username,
password: this.state.password
};
fetch("/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
loginData: loginData
})
})
.then((response) => {
return response.json();
})
.then((data) => {
if (data["Result"]) {
console.log(data["Result"]);
this.setState({ error: data["Result"] });
}
})
.catch((error) => {
console.log("Error: ", error);
});
}
render() {
return (
<div id="login-form-container">
<form id="login-form" onSubmit={this.handleSubmit} method="POST">
<ErrorMessage error={this.state.error} />
<input
type="text"
name="username"
placeholder="username"
autoComplete="username"
onFocus={e => (e.target.placeholder = "")}
onBlur={e => (e.target.placeholder = "username")}
value={this.state.username}
onChange={this.handleInputChange}
required
/>
<input
type="password"
name="password"
placeholder="password"
autoComplete="current-password"
onFocus={e => (e.target.placeholder = "")}
onBlur={e => (e.target.placeholder = "password")}
value={this.state.password}
onChange={this.handleInputChange}
required
/>
<button type="submit" name="submit">
Login
</button>
<p className="forgotten-password">Forgotten your password?</p>
</form>
</div>
);
}
}

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