ComboBox doesn't show after setState or forceUpdate - reactjs

my problem is that I want to get info If I'm authorized from API using axios.get before rendering the page. I did something like that. Everything is working perfectly but my with a role to choose doesn't show.
I'm new in react. "this.forceUpdate()" <- same problem
If I delete my authorization check, eliminate const{authorized} = this.state and {authorized ?(...) I see the combobox.
class RegisterComponent extends Component {
componentDidMount() {
this.checkAuthorizationStatus();
M.AutoInit();
}
checkAuthorizationStatus(){
axios.get(API_URL+`/logged_in`)
.then(response=>{
if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
this.setState({authorized:true})
}
else{
return <Redirect to="/login" />
}
})
}
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
role : 'ROLE_ADMIN',
hasCreationFailed: false,
showSuccessMessage: false,
authorized : false,
}
}
handleChange = (event) => {
this.setState(
{
[event.target.name]: event.target.value
}
)
}
submitClicked = () => {
console.log({login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]})
axios.post(API_URL + '/admin/register', {
login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]
})
.then((response) => {
this.setState({
showSuccessMessage: true,
hasCreationFailed: false
}
)
console.log(response)
})
.catch((error) => {
this.setState({
showSuccessMessage: false,
hasCreationFailed: true
})
console.log(error)
})
}
render() {
const{authorized} = this.state
return (
<React.Fragment>
{authorized ?(
<div className="row container">
<div className="col s10 offset-s1 l4 offset-l4">
<div className="purple-text accent-2"><h5>Create New Account</h5></div>
<div className="input-field">
<select value={this.state.role} onChange={this.handleChange} name="role">
<option value='ROLE_ADMIN'>Administrator</option>
<option value='ROLE_TABLE'>Klient</option>
<option value='ROLE_WORKER'>Pracownik</option>
</select>
</div>
<div className="input-field">
<input className="validate" type="text" id="username" name="username"
value={this.state.username} onChange={this.handleChange}/>
<label htmlFor="username">Username</label>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" value={this.state.password}
onChange={this.handleChange}/>
</div>
<button className="btn blue col l12 waves-effect waves-light"
onClick={this.submitClicked}>Zarejestruj użytkownika
</button>
{this.state.showSuccessMessage &&
<div className="green-text">Rejestracja zakończona powodzeniem</div>}
{this.state.hasCreationFailed && <div className="red-text">Rejestracja nie powiodła się</div>}
</div>
</div>
):(<></>)}
</React.Fragment>
)}
}
export default RegisterComponent
Could anyone help me?

Update the role property of state in your handleChange since your <select> uses value from this.state.role
handleChange = (event) => {
this.setState(
{
role: event.target.value // update 'role' property
}
)
}

Related

this.state not populating fields in editProfile.component

Newbie here. Basic question I know. I have made a 'newProfile' component using pretty much the same mechanics as this and it's working! Now I need an editProfile component that updates the Profile form with props from the database using params.id. The URL shows the .id piece is working when I click 'edit' on a profile in a profileList component that is also working. This code is not getting errors, but it is not showing state for each of the fields.
What am I missing?
`
export default class EditProfile extends Component {
constructor(props) {
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeFirst = this.onChangeFirst.bind(this);
this.onChangeLast = this.onChangeLast.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onChangeDob = this.onChangeDob.bind(this);
this.onChangeLocation = this.onChangeLocation.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username: '',
first: '',
last: '',
email: '',
password:'',
dob:'',
location:'',
}
}
componentDidMount() {
axios.get('http://localhost:5000/profiles/'+this.props.match.params.id)
.then(response => {
this.setState({
username: response.data.username,
first: response.data.first,
last: response.data.last,
email: response.data.email,
password: response.data.password,
dob: response.data.dob,
location: response.data.location
})
})
.catch(function (error) {
console.log(error);
})
}
componentDidMount() {
axios.get('http://localhost:5000/users/')
.then(response => {
if (response.data.length > 0) {
this.setState({
users: response.data.map(user => user.username),
})
}
})
.catch((error) => {
console.log(error);
})
}
onChangeProfilePic(e) {
this.setState({
profilePic: e.target.value
});
}
onChangeUsername(e) {
this.setState({
username: e.target.value
});
}
onChangeFirst(e) {
this.setState({
first: e.target.value
});
}
onChangeLast(e) {
this.setState({
last: e.target.value
});
}
onChangeEmail(e) {
this.setState({
email: e.target.value
});
}
onChangePassword(e) {
this.setState({
password: e.target.value
});
}
onChangeDob(e) {
this.setState({
dob: e.target.value
});
} onChangeLocation(e) {
this.setState({
location: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const profile = {
username: this.state.username,
first: this.state.first,
last: this.state.last,
email: this.state.email,
password: this.state.password,
dob: this.state.dob,
location: this.state.location,
}
console.log(profile);
axios.post('http://localhost:5000/profiles/update'+this.props.match.params.id, profile)
.then(res => console.log(res.data));
window.location = '/';
}
render() {
return (
<div>
<h3>Edit Profile
</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username:
</label>
<input
type="text"
className="form-control"
value={this.state.username}
onChange={this.onChangeUsername}
/>
</div>
<div className="form-group">
<label>First Name:
</label>
<input
type="text"
className="form-control"
value={this.state.first}
onChange={this.onChangeFirst}
/>
</div>
<div className="form-group">
<label>Last Name:
</label>
<input
type="text"
className="form-control"
value={this.state.last}
onChange={this.onChangeLast}
/>
</div>
<div className="form-group">
<label>Email:
</label>
<input
type="text"
className="form-control"
value={this.state.email}
onChange={this.onChangeEmail}
/>
</div>
<div className="form-group">
<label>Password:
</label>
<input
type="text"
className="form-control"
value={this.state.password}
onChange={this.onChangePassword}
/>
</div>
<div className="form-group">
<input type="submit" value="Save" className="btn btn-primary" />
</div>
</form>
</div>
)}
}
`
Here is the error I'm getting in the console.
react-dom.development.js:86 Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
at input
at div
at form
at div
at CreateProfile (http://localhost:3000/static/js/bundle.js:194:5)
at RenderedRoute (http://localhost:3000/static/js/bundle.js:44214:5)
at Routes (http://localhost:3000/static/js/bundle.js:44678:5)
at div
at Router (http://localhost:3000/static/js/bundle.js:44609:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:42779:5)
at App

needing page to pull just one user based on ID for editing but get them all

This is my edit user page and I would like it to pull one user at a time for editing.
When you click the pencil to edit I would like just the one user pulled but instead I get all of them like in the second image.
in the code below I map them out but have tried using filter and a reducer but no fix has worked as of yet. would an inline condition be better like the one below but have not figured how to get the right ID from the URL.
{Collectors.CollectorID === Collectors.CollectorID && <div><h2>1-30 days past due in Tandem – all credit types</h2> <p>{Collectors.CollectorCode}{Collectors.FinanceCompany}</p></div>}
import React from "react";
import axios from 'axios';
class UpdateUser extends React.Component {
constructor(props) {
super(props);
this.state = {
collectorList: [],
CollectorID: props.CollectorID,
ProgramBucketID: props.ProgramBucketID,
CollectorOptionsID: props.CollectorOptionsID,
FinanceCompanyID: props.FinanceCompanyID,
Active: '',
LastName: '',
CollectorCode: '',
Aging1to15: '',
Aging31to45: '',
Aging31to60: '',
AgingOver60: '',
ProgramBucketA: '',
ProgramBucketB: '',
ProgramBucketC: '',
ProgramBucketSU: '',
FinanceCompany: ''
}
this.handleActiveChange = this.handleActiveChange.bind(this);
this.handleAging115Change = this.handleAging115Change.bind(this);
this.handleAging3145Change = this.handleAging3145Change.bind(this);
this.handleAging3160Change = this.handleAging3160Change.bind(this);
this.handleAgingOver60Change = this.handleAgingOver60Change.bind(this);
this.handleProgramAChange = this.handleProgramAChange.bind(this);
this.handleProgramBChange = this.handleProgramBChange.bind(this);
this.handleProgramCChange = this.handleProgramCChange.bind(this);
this.handleProgramSUChange = this.handleProgramSUChange.bind(this);
}
componentDidMount(e) {
this.getCollectors()
}
handleActiveChange(e) {
this.setState({
Active: !this.state.Active
})
}
handleAging115Change() {
this.setState({
Aging1to15: !this.state.Aging1to15
})
}
handleAging3145Change() {
this.setState({
Aging31to45: !this.state.Aging31to45
})
}
handleAging3160Change() {
this.setState({
Aging31to60: !this.state.Aging31to60
})
}
handleAgingOver60Change() {
this.setState({
AgingOver60: !this.state.AgingOver60
})
}
handleProgramAChange() {
this.setState({
ProgramBucketA: !this.state.ProgramBucketA
})
}
handleProgramBChange() {
this.setState({
ProgramBucketB: !this.state.ProgramBucketB
})
}
handleProgramCChange() {
this.setState({
ProgramBucketC: !this.state.ProgramBucketC
})
}
handleProgramSUChange() {
this.setState({
ProgramBucketSU: !this.state.ProgramBucketSU
})
}
getCollectors = () => {
axios.get(`http://localhost:5000/getCollectors`)
.then((result) => result.data)
.then((result) => {
this.setState({collectorList: result});
});
};
onUpdateClick = CollectorID => {
axios.put(`http://localhost:5000/UpdateUser/${CollectorID}`, {
CollectorID: this.state.CollectorID,
CollectorOptionsID: this.state.CollectorOptionsID,
ProgramBucketID: this.state.ProgramBucketID,
FinanceCompanyID: this.state.FinanceCompanyID,
Active: this.state.Active,
LastName: this.state.LastName,
CollectorCode: this.state.CollectorCode,
Aging1to15: this.state.Aging1to15,
Aging31to45: this.state.Aging31to45,
Aging31to60: this.state.Aging31to60,
AgingOver60: this.state.AgingOver60,
ProgramBucketA: this.state.ProgramBucketA,
ProgramBucketB: this.state.ProgramBucketB,
ProgramBucketC: this.state.ProgramBucketC,
ProgramBucketSU: this.state.ProgramBucketSU,
FinanceCompany: this.state.FinanceCompany
});
};
render() {
// console.log(this.state);
return (
<div>
<h1>Update Collectors</h1>
<div className="wrapper">
{this.state.collectorList.map((Collectors) => (
<form className="updateUserForm" key={Collectors.CollectorID}>
<div className="updateUserItem">
<b>{Collectors.FirstName} {Collectors.LastName} | {Collectors.CollectorCode}</b>
{/*Active or inactive User*/}
<label>Active Status</label>
<input
type='checkbox'
name="Active"
value={this.state.Active}
defaultChecked={Collectors.Active === false ? false : true}
onChange={this.handleActiveChange}
/>
{/*Collector Last Name*/}
<label>Last Name</label>
<input
type="text"
name="LastName"
defaultValue={Collectors.LastName}
onChange={e => this.setState({
LastName: e.target.value
})}
/>
{/*Collector Code First Initial Middle Initial Last Initial*/}
<label>Collector Code</label>
<input
type="text"
name="CollectorCode"
defaultValue={Collectors.CollectorCode}
onChange={e => this.setState({
CollectorCode: e.target.value
})}
/>
{/*Aging Bucket selection section */}
<label>Aging Bucket</label>
<div className='newUserCheckboxContainer'>
<label className='newUserCheckboxLabel'>1-15<br/>
<input
type='checkbox'
className='AgingBucketCheckbox'
value={this.state.Aging1to15}
defaultChecked={Collectors.Aging1to15 === false ? false : true}
onChange={this.handleAging115Change}
/></label>
<label className='newUserCheckboxLabel'>31-45<br/>
<input
type='checkbox'
className='AgingBucketCheckbox'
value={this.state.Aging31to45}
defaultChecked={Collectors.Aging31to45 === false ? false : true}
onChange={this.handleAging3145Change}
/></label>
<label className='newUserCheckboxLabel'>31-60<br/>
<input
type='checkbox'
className='AgingBucketCheckboxsm'
value={this.state.Aging31to60}
defaultChecked={Collectors.Aging31to60 === false ? false : true}
onChange={this.handleAging3160Change}
/></label>
<label className='newUserCheckboxLabel'>Over 60<br/>
<input
type='checkbox'
className='AgingBucketCheckboxlg'
value={this.state.AgingOver60}
defaultChecked={Collectors.AgingOver60 === false ? false : true}
onChange={this.handleAgingOver60Change}
/></label>
</div>
{/*Progam code selection section*/}
<label>Program Bucket</label>
<div className='newUserCheckboxContainer'>
<label className='newUserCheckboxLabel'>A<br/>
<input
type='checkbox'
className='ProgramBucketChecbox'
value={this.state.ProgramBucketA}
defaultChecked={Collectors.ProgramBucketA === false ? false : true}
onChange={this.handleProgramAChange}
/></label>
<label className='newUserCheckboxLabel'>B<br/>
<input
type='checkbox'
className='ProgramBucketChecbox'
value={this.state.ProgramBucketB}
defaultChecked={Collectors.ProgramBucketB === false ? false : true}
onChange={this.handleProgramBChange}
/></label>
<label className='newUserCheckboxLabel'>C<br/>
<input
type='checkbox'
className='ProgramBucketChecbox'
value={this.state.ProgramBucketC}
defaultChecked={Collectors.ProgramBucketC === false ? false : true}
onChange={this.handleProgramCChange}
/></label>
<label className='newUserCheckboxLabel'>SU<br/>
<input
type='checkbox'
className='ProgramBucketChecbox'
value={this.state.ProgramBucketSU}
defaultChecked={Collectors.ProgramBucketSU === false ? false : true}
onChange={this.handleProgramSUChange}
/></label>
</div>
{/*Finance Company selection section*/}
<label>Finance Company</label>
<div className='newUserCheckboxContainer'>
<label className='newUserCheckboxLabel'>
<input
type="text"
name="FinanceCompany"
defaultValue={Collectors.FinanceCompany}
onChange={e => this.setState({
FinanceCompany: e.target.value
})}
/></label>
</div>
<button className="updateUserButton" onClick={() => this.onUpdateClick(Collectors.CollectorID) }>Update User</button>
</div>
</form>
))}
</div>
</div>
);
}
}
export default UpdateUser;
After going through some tests I found the below code works wonderfully if anyone is having this issue.
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
const UpdateUser = () => {
const { CollectorID } = useParams();
const [user, setUser] = useState({
Active: '',
FirstName: '',
LastName: '',
CollectorCode: ''
});
const { Active, FirstName, LastName, CollectorCode } = undefined || user;
const onInputChange = e => {
setUser({
...user, [e.target.name]: e.target.value,
Active: !Active });
};
useEffect(() => {
loadUser();
}, []);// eslint-disable-line react-hooks/exhaustive-deps
const loadUser = async () => {
const result = await axios.get(`http://localhost:5000/getCollectors/${CollectorID}`);
setUser(result.data[CollectorID - 1]);
// console.log(result.data[CollectorID - 1]);
};
const onSubmit = async e => {
e.preventDefault();
await axios.put(`http://localhost:5000/UpdateUser/${CollectorID}`, {
CollectorID: CollectorID,
Active: Active,
LastName: LastName,
CollectorCode: CollectorCode
});
console.log(CollectorID, Active, LastName, CollectorCode)
};
return (
<div className="previewWrapper">
<h1>Update Collector</h1>
{FirstName} {LastName} | {CollectorCode} - {CollectorID} {console.log(user)}
<form className="newUserForm" onSubmit={e => onSubmit(e)}>
<div className="newUserItem">
{/*Active or inactive User*/}
<label>Active</label>
<input
type='checkbox'
defaultValue={Active}
defaultChecked={Active}
onChange={e => onInputChange(e)}
/>
{/*Collector Last Name*/}
<label>Last Name</label>
<input
type="text"
placeholder="Last Name"
name="LastName"
defaultValue={LastName}
onChange={e => onInputChange(e)}
/>
{/*Collector Code First Initial Middle Initial Last Initial*/}
<label>Collector Code</label>
<input
type="text"
name="CollectorCode"
placeholder="Collector Code"
defaultValue={CollectorCode}
onChange={e => onInputChange(e)}
/>
<button className="newUserButton">Update Collector</button>
</div>
</form>
</div>
);
}
export default UpdateUser;

How can I get radio button value in React?

I have three radio buttons and I need to put the value of the selected one in inputs.reply, just like I did with inputs.name, inputs.email, inputs.phone and inputs.message. How can I do this? I know it's probably a very easy thing to do, but I've been trying for hours and it doesn't work.
import Head from 'next/head'
import React, { useState } from 'react'
export default () => {
const [status, setStatus] = useState({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
const [inputs, setInputs] = useState({
reply: '',
name: '',
phone: '',
email: '',
message: ''
})
function SubmitButton(){
if (inputs.name && inputs.email && inputs.message) {
return <button type="submit" className="btn-submit" disabled={status.submitting}> {!status.submitting ? !status.submitted ? 'Submit' : 'Submitted' : 'Submitting...'} </button>
} else {
return <button type="submit" className="btn-submit" disabled>Submit</button>
};
};
const handleResponse = (status, msg) => {
if (status === 200) {
setStatus({
submitted: true,
submitting: false,
info: { error: false, msg: msg }
})
setInputs({
reply: '',
name: '',
phone: '',
email: '',
message: ''
})
} else {
setStatus({
info: { error: true, msg: msg }
})
}
}
const handleOnChange = e => {
e.persist()
setInputs(prev => ({
...prev,
[e.target.id]: e.target.value
}))
setStatus({
submitted: false,
submitting: false,
info: { error: false, msg: null }
})
}
const handleOnSubmit = async e => {
e.preventDefault()
setStatus(prevStatus => ({ ...prevStatus, submitting: true }))
const res = await fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(inputs)
})
const text = await res.text()
handleResponse(res.status, text)
}
return (
<div className="contact">
<main>
<div className="content">
<div>
<h2>Get in touch!</h2>
<h3>How can we help you?</h3>
</div>
<form onSubmit={handleOnSubmit}>
<h4>How would you like us to get back to you?</h4>
<div className="form-group form-group-radio">
<div>
<input type="radio" onChange={handleOnChange} value="Phone" name="email-reply" id="reply-phone" />
<label className="radio-label" htmlFor="reply-phone">Phone</label>
</div>
<div>
<input type="radio" onChange={handleOnChange} value="E-mail" name="email-reply" id="reply-email" />
<label className="radio-label" htmlFor="reply-email">E-mail</label>
</div>
<div>
<input type="radio" onChange={handleOnChange} value="No reply needed" name="email-reply" id="no-reply" />
<label className="radio-label" htmlFor="no-reply">No reply needed</label>
</div>
</div>
<div className="form-group">
<input
id="name"
type="text"
name="name"
onChange={handleOnChange}
required
value={inputs.name}
className={inputs.name ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="name">Name</label>
</div>
<div className="form-group">
<input
id="email"
type="text"
name="email"
onChange={handleOnChange}
required
value={inputs.email}
className={inputs.email ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="email">Email</label>
</div>
<div className="form-group">
<input
id="phone"
type="tel"
name="phone"
onChange={handleOnChange}
required
value={inputs.phone}
className={inputs.phone ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="phone">Phone</label>
</div>
<div className="form-group">
<textarea
id="message"
onChange={handleOnChange}
required
value={inputs.message}
className={inputs.message ? "form-control active" : "form-control"}
/>
<label className="form-label" htmlFor="message">Message</label>
</div>
<SubmitButton />
{status.info.error && (
<div className="message-feedback error">
<p>Error: {status.info.msg}</p>
</div>
)}
{!status.info.error && status.info.msg && (
<div className="message-feedback success">
<p>Thanks for messaging us!</p>
<p>We'll get back to you soon.</p>
</div>
)}
</form>
</div>
</main>
</div>
)
}
Thank you.
Remove the id attribute from all of the <input type="radio" /> and instead add a name="reply" to all of them.
Now update handleOnChange, specifically this part
setInputs(prev => ({
...prev,
[e.target.id || e.target.name]: e.target.value
}))
You can update the handleOnChange method to check for the type of the target event and if its a radio button, you can update the radio state, otherwise use the dynamic key to update the state.
const handleOnChange = (e) => {
e.persist();
const key = e.target.type === "radio" ? "reply" : e.target.id;
setInputs((prev) => ({
...prev,
[key]: e.target.value
}));
setStatus({
submitted: false,
submitting: false,
info: { error: false, msg: null }
});
};

Storing data in multiple tables in react on the basis of role

I'm new to react and i'm building a website in which user is added on the basis of role. While adding user information, user selects a role in drop down. I have a table for Role in which only roles are kept(admin, teacher and team lead), a User table which contains user information( name, email password, etc) and a UserRole table which will have a userID and a roleID to represent which role is assigned to which user. I'm using asp.net core web-API to get and post data.
I just can't figure that out how to save roleID against the role that has been selected and userID of user in UserRole table.
can please someone help me with it?
Here is my react code of file Adduser.tsx
import * as React from 'react';
//import { ReactComponent } from '*.svg';
import '../css/form.css';
import Sidebar from '../Component/sidebar/sidebar';
const axios = require('axios');
class Adduser extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
teacherId: 0,
name: '',
email: '',
password: '',
confirmPassword: '',
gender: '',
question: [],
nameError: '',
passError: '',
emailError: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
componentWillMount() {
if (this.props.match.params.id != undefined) {
axios.get('https://localhost:44310/api/Users/' + this.props.match.params.id)
.then((response: any) => {
this.setState({
teacherId: response.data.teacherId,
name: response.data.name,
email: response.data.email,
password: response.data.password,
confirmPassword: response.data.confirmPassword,
gender: response.data.gender,
role: response.data.role,
question: []
});
})
.catch((error: any) => {
console.log(error);
});
}
}
handleChange = (event: any) => {
this.setState({ [event.target.name]: event.target.value }, () => this.validateName())
}
handlePasswordChange = (event: any) => {
this.setState({ [event.target.name]: event.target.value }, () => this.validatePassword())
}
validateName() {
const { name } = this.state;
this.setState(
{ nameError: name.length > 3 ? null : 'Name must contain atleast 3 characters' }
// passError: password.length > 3 || password ? null : 'Password must contain atleast 6 characters'}
)
}
validatePassword() {
const { password } = this.state;
this.setState({
passError: password.length > 6 ? null : 'Password must contain atleast 6 characters'
}
)
}
validateEmail(email: any) {
const pattern = /[a-zA-Z0-9]+[\.]?([a-zA-Z0-9]+)?[\#][a-z]{3,9}[\.][a-z]{2,5}/;
const result = pattern.test(email);
if (result === true) {
this.setState({
emailError: false,
email: email
})
} else {
this.setState({
emailError: true
})
}
// email = $('email');
// var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// if (filter.test(email.value)) {
// // Yay! valid
// return '';
// }
// else
// return 'invalid email';
}
handleSubmit(event: any) {
event.preventDefault();
if (this.props.match.params.id != undefined) {
const { password, confirmPassword } = this.state
if (password !== confirmPassword) {
alert('passwords do not match')
}
else {
axios.put(`https://localhost:44310/api/Users/${this.props.match.params.id}`, this.state)
.then((response: any) => {
this.props.history.push('/');
})
.catch(function (error: any) {
console.log(error);
});
}
} else {
const { password, confirmPassword, name } = this.state
if (password !== confirmPassword) {
alert('passwords do not match')
}
else {
axios.post('https://localhost:44310/api/Users/', this.state)
.then((response: any) => {
console.log(response);
alert('User has been added successfully')
})
.catch(function (error: any) {
console.log(error);
alert('Sorry! Your request can not be processed at the moment')
});
}
}
}
render() {
return (
<div className="row">
<div className=" col-lg-2">
<Sidebar />
</div>
<div className="col-lg-10">
<div className="content" >
<div className="container-fluid">
<div className="row" >
<div className="col-lg-3"> </div>
<div className="col-lg-6" style={{ paddingTop: "30px" }}>
<div id="ui">
{this.props.match.params.id != undefined ? <h1 style={{ marginTop: "15px" }}>EDIT ACCOUNT</h1> : <h1 style={{ marginTop: "15px" }}>ADD ACCOUNT</h1>}
<form className="form-group" method="post" onSubmit={this.handleSubmit} autoComplete="off">
<label> Name:</label>
<div className="name">
<input type="text"
onChange={this.handleChange}
name="name"
value={this.state.name}
className={`form-control ${this.state.nameError ? 'is-invalid' : ''}`}
placeholder="Enter username " required
onBlur={this.validateName.bind(this)} />
<div className="invalid-feedback">Name must be longer than 3 characters</div>
</div>
<br />
<label> Email:</label>
<div className="mail">
<input type="email" name="email" value={this.state.email} onChange={this.handleChange} className="form-control" placeholder="Enter E-mail" required />
<div className="invalid-feedback">Email is invalid</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<label> Password:</label>
<div className="pass">
<input type="password" name="password" value={this.state.password} onChange={this.handlePasswordChange} className={`form-control ${this.state.passError ? 'is-invalid' : ''}`} id="pwd" placeholder="Enter password" required onBlur={this.validatePassword.bind(this)} />
<div className="invalid-feedback">Password must be longer than 6 characters</div>
</div>
</div>
<div className="col-lg-6">
<label> Re-type Password:</label>
<div className="pass1">
<input type="password" name="confirmPassword" value={this.state.pass1} onChange={this.handleChange} className="form-control" id="pwd1" placeholder="Re-type password" required />
</div>
</div>
<br />
<div className="col-lg-12">
<select className="form-control" name="gender" value={this.state.gender} onChange={this.handleChange} id="sel" style={{ marginTop: "35px" }} required>
<option>Choose Gender</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
<br />
<div className="col-lg-12">
<select className="form-control" name="role" value={this.state.role} onChange={this.handleChange} id="sel" style={{ marginTop: "35px" }} required>
<option>Role</option>
<option>Admin</option>
<option>Teacher</option>
<option>TeamLead</option>
</select>
</div>
<br />
<div className="col-lg-12">
{/* <Link className="nav-link" to="/"> */}
<input type="submit" name="submit" value="submit" className="btn btn-primary btn-block btn-lg" style={{ marginTop: "20px" }} />
{/* </Link> */}
</div>
</div>
</form>
</div>
</div>
<div className="col-lg-3"></div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Adduser;

How can I pass data using <Redirect> in react router v4?

The situation is that I use axios gain data from back-end and I want to redirect from current page to another page as well as passing some data.
How can I pass data when I use <Redirect> to redirect?
I am using code like below, and I can't get 'profile' at the destination page. No matter, this.props or this.state
I understand that using react-router-redux is a better choice.
import React, { Component } from 'react'
import axios from 'axios'
import { Redirect } from 'react-router'
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
emailError: 'Please fill in email',
password: '',
passwordError: 'Please fill in password',
redirect: false,
profile: ''
}
this.handleEmail = (e) => {
var email = e.target.value
var emailError = ''
if (email === null)
emailError = 'Please fill in email'
this.setState({
email: email,
emailError: emailError
})
}
this.handlePassword = (e) => {
var password = e.target.value
var passwordError = ''
if (password === null)
passwordError = 'Please fill in password'
this.setState({
password: password,
passwordError: passwordError
})
}
this.handleSubmit = (e) => {
e.preventDefault()
if (this.state.emailError)
alert(this.state.emailError)
else if (this.state.passwordError)
alert(this.state.passwordError)
else {
axios.post('/user/login', {
email: this.state.email,
password: this.state.password
}).then(response => {
if (response.data !== 'fail') {
this.setState({
redirect: true,
profile: response.data
})
}
})
}
}
}
render() {
const { redirect, profile } = this.state
if (redirect)
return (<Redirect to={{
pathname: '/user/profile',
state: { referrer: this.state.profile }
}} />)
return (
<div className="content user">
<div className="container">
<div className="row">
<div className="col-xs-12">
<h1>Log In Your Tutor Profile</h1>
<form role="form" noValidate>
<div className="row">
<div className="col-xs-12">
<label htmlFor="email">Email</label>
<div className="form-group">
<input id="email" type="text" className="form-control" value={this.state.email} onChange={this.handleEmail} name="email" required/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12">
<label htmlFor="password">Password</label>
<div className="form-group">
<input id="password" type="password" className="form-control" value={this.state.password} onChange={this.handlePassword} name="password" required/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12">
<div className="form-group">
<button className="btn btn-primary submit" onClick={this.handleSubmit}>LOG IN YOUR PROFILE</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}
The way you are passing your state to the Redirect is correct, the only place the problem should be is how you are accessing it. State can be accessed like this.props.location.state. However if you directly route to the path then state won't we available so you need to add a check
Access your state like
this.props.location.state && this.props.location.state.referrer

Resources