How can I get radio button value in React? - reactjs

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 }
});
};

Related

I cannot understand how setValue is working in init() which used in useEffect?

I know that useEffect( without any dependencies) only work on Mount So how state updates by setValues in init() here??
I am beginner in mern stack so please if you wnat any info please comment
//Code snippet
const init = () => {
getCategories().then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
categories: data,
formData: new FormData()
});
}
});
};
useEffect(() => {
init();
}, []);
//full code for help
import React, { useState, useEffect } from 'react';
import Layout from '../core/Layout';
import { isAuthenticated } from '../auth';
import { Link } from 'react-router-dom';
import { createProduct, getCategories } from './apiAdmin';
const AddProduct = () => {
const [values, setValues] = useState({
name: '',
description: '',
price: '',
categories: [],
category: '',
shipping: '',
quantity: '',
photo: '',
loading: false,
error: '',
createdProduct: '',
redirectToProfile: false,
formData: ''
});
const { user, token } = isAuthenticated();
const {
name,
description,
price,
categories,
category,
shipping,
quantity,
loading,
error,
createdProduct,
redirectToProfile,
formData
} = values;
// load categories and set form data
const init = () => {
getCategories().then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
categories: data,
formData: new FormData()
});
}
});
};
useEffect(() => {
init();
}, []);
const handleChange = name => event => {
const value = name === 'photo' ? event.target.files[0] : event.target.value;
formData.set(name, value);
setValues({ ...values, [name]: value });
};
const clickSubmit = event => {
event.preventDefault();
setValues({ ...values, error: '', loading: true });
createProduct(user._id, token, formData).then(data => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
name: '',
description: '',
photo: '',
price: '',
quantity: '',
loading: false,
createdProduct: data.name
});
}
});
};
const newPostForm = () => (
<form className="mb-3" onSubmit={clickSubmit}>
<h4>Post Photo</h4>
<div className="form-group">
<label className="btn btn-secondary">
<input onChange={handleChange('photo')} type="file" name="photo" accept="image/*" />
</label>
</div>
<div className="form-group">
<label className="text-muted">Name</label>
<input onChange={handleChange('name')} type="text" className="form-control" value={name} />
</div>
<div className="form-group">
<label className="text-muted">Description</label>
<textarea onChange={handleChange('description')} className="form-control" value={description} />
</div>
<div className="form-group">
<label className="text-muted">Price</label>
<input onChange={handleChange('price')} type="number" className="form-control" value={price} />
</div>
<div className="form-group">
<label className="text-muted">Category</label>
<select onChange={handleChange('category')} className="form-control">
<option>Please select</option>
{categories &&
categories.map((c, i) => (
<option key={i} value={c._id}>
{c.name}
</option>
))}
</select>
</div>
<div className="form-group">
<label className="text-muted">Shipping</label>
<select onChange={handleChange('shipping')} className="form-control">
<option>Please select</option>
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div className="form-group">
<label className="text-muted">Quantity</label>
<input onChange={handleChange('quantity')} type="number" className="form-control" value={quantity} />
</div>
<button className="btn btn-outline-primary">Create Product</button>
</form>
);
const showError = () => (
<div className="alert alert-danger" style={{ display: error ? '' : 'none' }}>
{error}
</div>
);
const showSuccess = () => (
<div className="alert alert-info" style={{ display: createdProduct ? '' : 'none' }}>
<h2>{`${createdProduct}`} is created!</h2>
</div>
);
const showLoading = () =>
loading && (
<div className="alert alert-success">
<h2>Loading...</h2>
</div>
);
return (
<Layout title="Add a new product" description={`G'day ${user.name}, ready to add a new product?`}>
<div className="row">
<div className="col-md-8 offset-md-2">
{showLoading()}
{showSuccess()}
{showError()}
{newPostForm()}
</div>
</div>
</Layout>
);
};
export default AddProduct
You're right that the useEffect without any dependencies will run once on mount. So that means that the function init() is gonna be called at least once on mount, right? So whatever action you have in your init function will be called once. You don't need dependencies in order to set a state.

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;

Why is my input field not editable even after adding onChange function - react

I am a new learner in react, I tried a simple login form which takes user input and passes it to backend. This application is also written to create tokens if the login credentials are correct. In order to take user input I have added the onChange() function and called it for each input field, however the it is still not editable. I couldn't find the error. I also have added onSubmit() function implementation. I did try various other ways of calling the onChange function, however it wasnt successful.
const [formData, setFormData] = useState({
clientEmail: "",
clientPassword: "",
errorMsg: false,
loadingSpinner: false,
});
// destructure form data
const { clientEmail, clientPassword, errorMsg, loadingSpinner } = formData;
const handleChange = (evt) => {
setFormData({
...formData,
[evt.target.name]: evt.target.value,
errorMsg: "",
});
};
const handleSubmit = (evt) => {
evt.preventDefault();
//form validation
if (isEmpty(clientEmail) || isEmpty(clientPassword)) {
setFormData({
...formData,
errorMsg: "All field are Required",
});
} else if (!isEmail(clientEmail)) {
setFormData({
...formData,
errorMsg: "Invalid Email new",
});
} else {
const { clientEmail, clientPassword} = formData;
const data = {
clientEmail,
clientPassword,
};
setFormData({
...formData,
loadingSpinner: true,
});
ClientLoginUser(data)
.then((response) => {
console.log(response);
setClientAuthentication(response.data.token, response.data.clients);
if (isClientAuthenticated()) {
console.log("client Successful");
history.push("./clientDashboard");
}
})
.catch((err) => {
console.log("client login api controller error: ", err);
setFormData({
...formData,
errorMsg:err.response.data.errorMessage,
loading:false
});
});
}
};
const showLoginForm = () => (
<Fragment>
<div className="card px-5 py-5">
<div className="card-body">
<h5 className="card-title text-center pb-3">Client Login</h5>
<form className="login-form"
onSubmit={handleSubmit}
noValidate>
{/* Email */}
<div className="form-group">
<input
type="email"
className="form-control"
name="email"
value={clientEmail}
placeholder="Email"
onChange={handleChange}
/>
</div>
{/* Password */}
<div className="form-group">
<input
type="password"
className="form-control"
name="password"
value={clientPassword}
placeholder="Password"
onChange={handleChange}
/>
</div>
{/* Submit button */}
<div className="form-group pt-3">
<button
type="submit"
className="btn btn-primary btn-lg btn-block"
>
Login
</button>
</div>
</form>
</div>
</div>
</Fragment>
);
/****************************
* Render
****************************/
return (
<div className="login-container">
<GridWrapper>
<div className="container-fluid">
<div className="row px-4 vh-100">
<div className="col-12 col-md-8 my-auto pl-5">
<img
src="/images/welcomeLogo.png"
className="img-fluid"
alt="Logo"
/>
</div>
<div className="col-12 col-md-3 align-self-center">
{errorMsg && showErrorMsg(errorMsg)}
{loadingSpinner && (
<div className="text-center pb-5">{showLoading()}</div>
)}
{showLoginForm()}
</div>
</div>
</div>
</GridWrapper>
</div>
);
};
// return <p>ClientLogin Component</p>;
The name in input is not exactly the same as in formData state
you got this state
const [formData, setFormData] = useState({
clientEmail: "",
clientPassword: "",
errorMsg: false,
loadingSpinner: false,
});
which contain data like clientEmail
<input
type="email"
className="form-control"
name="email"
value={clientEmail}
placeholder="Email"
onChange={handleChange}
/>
which contains name="email"
in handleChange Function
const handleChange = (evt) => {
setFormData({
...formData,
[evt.target.name]: evt.target.value,
errorMsg: "",
});
};
you contains [evt.target.name]: evt.target.value
thats mean you are trying to assign new Values to formData.email not to formData.clientEmail
there are two solution
first you can change
const [formData, setFormData] = useState({
email: "",
...
});
or you can
<input
type="email"
className="form-control"
name="clientEmail"
value={clientEmail}
placeholder="Email"
onChange={handleChange}
/>

value of the option selected not passing in react

Trying to get a response when clicking and store the selected option from the selected value genre, not sure how to add a select new state variable or a post method. When the option is clicked the click handler is not called with the selected options so that we can add it to the state. My genre is also seen as undefined when I don't click on the the text type.
Feedback.js
import React, { useState } from "react";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.min.css";
import Layout from "./Layout";
const Feedback = () => {
const [values, setValues] = useState({
name: "",
artist: "",
songTitle: "",
email: "",
message: "",
phone: "",
genre: "",
uploadedFiles: [],
buttonText: "Submit",
uploadPhotosButtonText: "Upload files",
});
// destructure state variables
const {
name,
artist,
songTitle,
label,
email,
message,
phone,
genre,
uploadedFiles,
buttonText,
uploadPhotosButtonText,
} = values;
// destructure env variables
const {
REACT_APP_API,
REACT_APP_CLOUDINARY_CLOUD_NAME,
REACT_APP_CLOUDINARY_UPLOAD_SECRET,
} = process.env;
// event handler
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
setValues({ ...values, buttonText: "...sending" });
// send to backend for email
console.table({ name, email, phone, message, uploadedFiles, genre });
axios({
method: "POST",
url: `${REACT_APP_API}/feedback`,
data: {
name,
artist,
songTitle,
label,
email,
genre,
phone,
message,
uploadedFiles,
},
})
.then((response) => {
// console.log('feedback submit response', response);
if (response.data.success) toast.success("Thanks for your feedback");
setValues({
...values,
name: "",
artist: "",
songTitle: "",
label: "",
phone: "",
email: "",
genre: "",
message: "",
uploadedFiles: [],
buttonText: "Submitted",
uploadPhotosButtonText: "Uploaded",
});
})
.catch((error) => {
// console.log('feedback submit error', error.response);
if (error.response.data.error) toast.error("Failed! Try again!");
});
};
function onChangeInput(value) {
console.log(value);
}
const uploadWidget = () => {
window.cloudinary.openUploadWidget(
{
cloud_name: REACT_APP_CLOUDINARY_CLOUD_NAME,
upload_preset: REACT_APP_CLOUDINARY_UPLOAD_SECRET,
tags: ["ebooks"],
},
function (error, result) {
// console.log(result);
setValues({
...values,
uploadedFiles: result,
uploadPhotosButtonText: `${
result ? result.length : 0
} Photos uploaded`,
});
}
);
};
const feedbackForm = () => (
<React.Fragment>
<div className="form-group">
<button
onClick={() => uploadWidget()}
className="btn btn-outline-secondary btn-block p-5"
>
{uploadPhotosButtonText}
</button>
</div>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label className="text-muted">Description</label>
<textarea
onChange={handleChange("message")}
type="text"
className="form-control"
value={message}
required
></textarea>
</div>
<div className="form-group">
<label className="text-muted">Your Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("name")}
value={name}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Your Email</label>
<input
className="form-control"
type="email"
onChange={handleChange("email")}
value={email}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Your Phone</label>
<input
className="form-control"
type="number"
onChange={handleChange("phone")}
value={phone}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Artist Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("artist")}
value={artist}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Song Title</label>
<input
className="form-control"
type="text"
onChange={handleChange("songTitle")}
value={songTitle}
required
/>
</div>
<div className="form-group">
<label className="text-muted">Record Label Name</label>
<input
className="form-control"
type="text"
onChange={handleChange("label")}
value={label}
/>
</div>
<div className="form-group">
<label className="text-muted">Music Genre:</label>
<select
className="form-control"
value={genre}
type="select"
onChange={handleChange("genre")}
>
<option value="steak">Steak</option>
<option value="sandwich">Sandwich</option>
<option value="dumpling">Dumpling</option>
</select>
</div>
<button className="btn btn-outline-primary btn-block">
{buttonText}
</button>
</form>
</React.Fragment>
);
return (
<Layout>
<ToastContainer />
<div className="container text-center">
<h1 className="p-5">Feedback Online</h1>
</div>
<div className="container col-md-8 offset-md-2">{feedbackForm()}</div>
<br />
<br />
<br />
</Layout>
);
};
export default Feedback;

ComboBox doesn't show after setState or forceUpdate

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
}
)
}

Resources