How can I pass email displaying in DialogContentText to axios put request - reactjs

How can I pass ratePlyrEmail to calculateAvgRating() during on click on submit button.
The player email will displays randomly in the <Input type="hidden" name="playertorate" value={email} onChange={onChange}></Input> of DialogContentText every time when the user click on Enter Player Rating button. I have added onChange in the DialogContentText. Now I am getting only rating and loginUserEmail in server side.
const [ratePlyrEmail, setRatePlyrEmail] = useState({ playertorate: ''});
const [rating, setRating] = useState({
shooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [ratingTotal, setRatingTotal] = useState(0);
const onChange = e => {
e.persist();
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
const rateEmailValue = {
...ratePlyrEmail,
[e.target.name]: e.target.value
}
setRatePlyrEmail(rateEmailValue);
ratingCalculation(ratingValues);
};
const ratingCalculation = ratingValues =>{
const {
shooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(shooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setRatingTotal(finalAvg);
return ratingTotal ;
}
const calculateAvgRating = (rating) => {
const sendPlayerRating = async () => {
try {
const params = {
email: loginUserEmail,
};
const res = await axios.put('http://localhost:8000/service/playerrating', {ratingTotal:rating}, {params} );
if (res.data.success) {
//rest of code to continue here...
}
else {
console.log(res.data.message);
}
} catch (e) {
console.log(e.response.data.message);
}
}
sendPlayerRating();
};
<div className="container">
<div className="weeklycount_graph_section">
<div>
<Button className="playerRatingBtn" variant="outlined" color="primary" onClick={() => handleClickOpen(setRandPlayerRating())}>
Enter Player Rating
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="skills-area"
>
<DialogTitle id="skills-area">Rate the skills of a player</DialogTitle>
<DialogContent>
{
randPlayers.map(({email, name, photo}) =>(
<DialogContentText key="id">
<Avatar alt="player" src={photo}/>
<Input type="hidden" name="playertorate" value={email} onChange={onChange}></Input>
</DialogContentText>
))
}
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="shooting"
label="Shooting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="dribbling"
label="Dribbling"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballcontrol"
label="Ball Control"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="sprinting"
label="Sprinting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="fitness"
label="Fitness"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button onClick={() => handleClose(calculateAvgRating((ratingCalculation(rating))))} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</div>
</div>
</div>

Related

Passing a function and parameters with onclick in react

i am trying to create a dynamic form where a user can enter the details of a guest list. I also want to be on every row a button called "email" where the user can click on it and an automatically generated email would be sent to the guest on that row. i have created the dynamic form and i have a fun a function that sends emails using (mailjs) what i cant do is pass the details of that particular row to the onlcick function so the email is sent to the right guest
my form code :
const useStyles = makeStyles((theme)=>({
root:{
"& .MuiTextField-root":{
margin: theme.spacing(1),
}
},
button:{
margin: theme.spacing(1)
}
}))
function Guests () {
const classes=useStyles()
const [inputFields, setInputField] = useState([
{firstName: "", lastName:"", email:"", rsvp:"", menue:""},
])
const handleSubmit =(e) =>{
e.preventDefault();
console.log("input fields", inputFields)
}
const handleChangeInput = (index, event) =>{
console.log(index, event.target.name)
const values =[...inputFields];
values[index][event.target.name] = event.target.value
setInputField(values)
}
const handleAddField = () =>{
setInputField([...inputFields,{firstName: "", lastName:"", email:"", rsvp:"", menue:""}])
}
const handleRemoveField =(index) =>{
const values = [...inputFields]
values.splice(index, 1)
setInputField(values)
}
return (
<Container>
<h1> Your Guest List</h1>
<form className={classes.root} onSubmit={handleSubmit}>
{inputFields.map((inputField, index)=>(
<div key={index}>
<TextField
name="firstName"
label="First Name"
value={inputField.firstName}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="lastName"
label="Last Name"
value={inputField.lastName}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="email"
label="Email"
value={inputField.email}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="rsvp"
label="RSVP"
value={inputField.rsvp}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="menue"
label="Menu Choice"
value={inputField.menue}
onChange={event => handleChangeInput(index, event)}
/>
<Button className={classes.button}
vareient="contained"
color="secondary"
>Send email</Button>
<IconButton
onClick={()=> handleRemoveField(index)}>
<RemoveIcon />
</IconButton>
<IconButton
onClick={() => handleAddField()}>
<AddIcon />
</IconButton>
</div>
))}
<Button
className={classes.button}
vareient="contained"
color="secondary"
type="submit"
onClick={handleSubmit}
endIcon={<Icon>save</Icon>}>
Save Guest List
</Button>
</form>
</Container>
)
}
export default Guests
my email function is :
function sendEmail (event){
event.preventDefault();
emailjs.sendForm(service,template,event.target,hero).then(res=>{
console.log(res)
alert("email sent thank you");
}).catch(err=> console.log(err));
}
Many thanks for you help

Unable to reset value in State of React

export default function Register() {
const [formData, setformData] = useState({
name: "",
emailid: "",
password: "",
password2: "",
});
const [formHelperText, setFormHelperText] = useState({
formHelperTextname: "",
formHelperTextemailid: "",
formHelperTextpassword: "",
formHelperTextpassword2: "",
});
const { name, emailid, password, password2 } = formData;
const {
formHelperTextname,
formHelperTextemailid,
formHelperTextpassword,
formHelperTextpassword2,
} = formHelperText;
const onChange = (e) => {
setformData({ ...formData, [e.target.name]: e.target.value });
};
let onSubmit = (e) => {
e.preventDefault();
debugger;
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
setFormHelperText({
...formHelperText,
formHelperTextname: "",
formHelperTextemailid: "",
});
if (name.length === 0) {
setFormHelperText({
...formHelperText,
formHelperTextname: "Enter your name",
});
}
else if (emailid.length === 0) {
setFormHelperText({
...formHelperText,
formHelperTextemailid: "Enter your email",
});
} else if (!emailid.match(mailformat)) {
setFormHelperText({
...formHelperText,
formHelperTextemailid: "Enter valid email",
});
}
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<form className={classes.form} noValidate onSubmit={onSubmit}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="name"
label="Name"
name="name"
value={name}
onChange={onChange}
autoFocus
error={formHelperTextname.length > 0}
helperText={formHelperTextname}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="emailid"
value={emailid}
onChange={onChange}
autoComplete="email"
error={formHelperTextemailid.length > 0}
helperText={formHelperTextemailid}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
value={password}
onChange={onChange}
error={formHelperTextpassword.length > 0}
helperText={formHelperTextpassword}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password2"
label="Retype Password"
type="password"
id="password2"
value={password2}
onChange={onChange}
error={formHelperTextpassword2.length > 0}
helperText={formHelperTextpassword2}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
<Grid container>
<Grid item xs></Grid>
<Grid item>
<Link href="/" variant="body2">
{"Already have an account? Sign In"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
When I'm trying to reset the value of formHelperTextname onSubmit function. The value is not updating to an empty string.
The value is set inside the IF condition but before the if condition when I try to reset the value of formhelperText it's not working
When I'm trying to reset the value of formHelperTextname onSubmit function. The value is not updating to an empty string.
The value is set inside the IF condition but before the if condition when I try to reset the value of formhelperText it's not working
States cannot be assigned immediately after they are changed. It is necessary to listen to State and do the same.
You can review the revised code below.
I hope I helped.
const [isClear, setIsClear] = useState(false);
useEffect(() => {
if (isClear) {
setFormHelperText({
...formHelperText,
formHelperTextname: "",
formHelperTextemailid: "",
});
}
}, [isClear]);
let onSubmit = (e) => {
e.preventDefault();
debugger;
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
setIsClear(true);
if (name.length === 0) {
setFormHelperText({
...formHelperText,
formHelperTextname: "Enter your name",
});
}
else if (emailid.length === 0) {
setFormHelperText({
...formHelperText,
formHelperTextemailid: "Enter your email",
});
} else if (!emailid.match(mailformat)) {
setFormHelperText({
...formHelperText,
formHelperTextemailid: "Enter valid email",
});
}
};

React hook form popular form with Material UI

I am trying to use react hook form with Material UI. At first, I want to populate the fields(textboxes, selects, autocompletes) after I fetch the user profile. How can I do that?
const [profileData, setProfileData] = useState(null);
const { control, handleSubmit, register, reset } = useForm();
useEffect(() => {
const getProfileData = async () => {
try {
const data = await api.get(profiles.getById, { id: profileId });
setProfileData(data);
} catch (err) {
console.log(`error getting: ${err}`);
}
};
getProfileData();
}, [profileId]);
<form onSubmit={handleSubmit(onSubmit)}>
<Flexbox flexDirection="column">
<Flexbox className="form-item">
<Select name="title" value={currentProfile.email}>
{dummyData.namePrefixes.map(index => (
<MenuItem key={index}>{index}</MenuItem>
))}
</Select>
<TextField
inputRef={register}
name="Name"
label="* Name"
InputLabelProps={{
shrink: true
}}
variant="outlined"
placeholder="Name"
className="form-item-full"
/>
</Flexbox>
<TextField
inputRef={register}
label="* Hospital Name"
name="hospital"
className="form-item"
placeholder="Hospital"
InputLabelProps={{
shrink: true
}}
variant="outlined"
/>
<Autocomplete
className="form-item"
options={countries}
getOptionLabel={option => option.name}
renderInput={params => (
<TextField
{...params}
label="Country"
placeholder="Select a Country"
InputLabelProps={{
shrink: true
}}
variant="outlined"
/>
)}
/>
const [profileData, setProfileData] = useState(null);
const { control, handleSubmit, register, reset } = useForm();
useEffect(() => {
getProfileData();
}, []);
const getProfileData = async () => {
try {
const data = await api.get(profiles.getById, { id: profileId });
setProfileData(data);
} catch (err) {
console.log(`error getting: ${err}`);
setProfileData(null);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
inputRef={register}
name="Name"
label="* Name"
InputLabelProps={{
shrink: true
}}
value={profileData?.name}
variant="outlined"
placeholder="Name"
className="form-item-full"
/>
<TextField
inputRef={register}
label="* Hospital Name"
name="hospital"
className="form-item"
placeholder="Hospital"
InputLabelProps={{
shrink: true
}}
value={profileData?.hospitalName}
variant="outlined"
/>
</form>
)

Validations not triggered during on click on submit button

I would like to display required, min 1 and max 5 validations in following fields in material-ui dialog. At the moment I have added for one field, but some how validation is not displaying during on click on submit button in dialog. Could someone please advise me on how can i fix the problem.
demo link added here:
https://codesandbox.io/s/tender-wood-3jrwu?file=/src/App.js
const App = () => {
const [rating, setRating] = useState({
ballshooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [ratingTotal, setRatingTotal] = useState(0);
const [open, setOpen] = React.useState(false);
const { handleSubmit, register, errors } = useForm();
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const onChange = e => {
e.persist();
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
ratingCalculation(ratingValues);
};
const ratingCalculation = ratingValues => {
const {
ballshooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(ballshooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setRatingTotal(finalAvg);
return ratingTotal;
};
return (
<form className="ratingForm">
<Button
className="playerRatingBtn"
onClick={() => handleClickOpen()}
variant="outlined"
color="primary"
>
Enter Player Rating
</Button>
<Dialog open={open} onClose={handleClose} aria-labelledby="skills-area">
<DialogTitle id="skills-area">Rate the skills of a player</DialogTitle>
<DialogContent>
<label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballshooting"
label="Ball Shooting"
type="text"
fullWidth
min={1}
max={5}
ref={register({
required: "Soccer ball shooting skill is required !"
})}
/>
<span className="newsErrorTextFormat">
{errors.shooting && errors.shooting.message}
</span>
</label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="dribbling"
label="Dribbling"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballcontrol"
label="Ball Control"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="sprinting"
label="Sprinting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="fitness"
label="Fitness"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button type="submit" onClick={() =>
handleClose(
handleSubmit(calculateAvgRating(ratingCalculation(rating)))
)
} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</form>
);
};
export default App;

how to edit a textfield values in reactjs

Here i add my sample code.i have a static values getting from state now i want to change this values
render() {
console.log(this.props.selectedVal);
var name,
gender,
city = "";
this.props.data.map((row, index) => {
// console.log(index);
if (this.props.selectedVal === index) {
gender = row[0];
name = row[1];
city = row[2];
}
return [];
});
return (
<Dialog
open={this.props.open}
onClose={this.handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<h1>Edit User</h1>
<DialogContent>
<DialogContentText id="alert-dialog-description" />
<Formik
initialValues={{ name: "", gender: "", city: "" }}
onSubmit={values => console.log(values)}
>
{props => (
<form>
<TextField margin="dense" id="name" label="Name" value={name} />
<br />
<TextField
margin="dense"
id="gender"
label="Gender"
value={gender}
/>
<br />
<TextField margin="dense" label="City" value={city} />
</form>
)}
</Formik>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
RESET
</Button>
<Button onClick={this.handleClose} color="primary" autoFocus>
SUBMIT
</Button>
</DialogActions>
</Dialog>
);
}
I am getting the values from the table row.Now i want to change these values using formik. How can I edit these values
Add a onChange listener in your textfield and map the value to a state variable:
textChange(e) {
const value = e.target.value
this.setState({ value })
}
render() {
return (
<TextField value={this.state.value} onChange={this.textChange} .. />
)
}
If you want to handle more values from different textfields using one method try something like this:
textChange(e) {
const id = e.target.id
const value = e.target.value
this.setState({ [id]: value })
}
render() {
return (
<TextField id="gender" value={this.state.gender} onChange={this.textChange} .. />
<TextField id="dense" value={this.state.dense} onChange={this.textChange} .. />
)
}
It seems like you get data with props from parent component. And, if I get it wright, question is how to change state of parent component? You need to add to props function binded to parent`s context and use setState there.

Resources