So this may be something simple but I'm hitting a roadblock. I want to take in a form input but can't seem to figure out how to append the value correctly so its appending string is captured.
I'm using Formik with yup in react.
<InputGroup>
<Field
id="appended-input"
name="domain_url"
type="text"
value={values.domain_url}
className={
"form-control" +
(errors.domain_url && touched.domain_url
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="domain_url"
component="div"
className="invalid-feedback"
/>
<InputGroupAddon addonType="append">
.localhost
</InputGroupAddon>
</InputGroup>
Any help would be appreciated. I just want to get the .localhost to be automatically added to the input items. for this field. I thought I could do something like value=({values.domain_url} + ".localhost") but that didn't seem to work and as you may already tell I am very new to javascript.
Thank you!
Full code below, I'm also having issues with datepicker displaying within the formik state, and then there's how to even get the values to push to my getTenant(function) to be passed to my api.
static propTypes = {
addTenant: PropTypes.func.isRequired,
};
onSubmit = (values) => {
values.preventDefault();
this.props.addTenant(values);
};
render() {
const {
domain_url,
schema_name,
name,
config,
} = this.state;
const TenantSchema = Yup.object().shape({
domain_url: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client URL header is required"),
schema_name: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client db name is required"),
name: Yup.string()
.max(255, "Must be shorter than 255 characters")
.required("Client name is required"),
});
return (
<div className={s.root}>
<Formik
initialValues={{
domain_url: "",
schema_name: "",
client_name: "",
config: [
{
date: "",
Tenant_description: "",
},
],
}}
// validationSchema={TenantSchema} this is commented off because it breaks
submittions
onSubmit={(values, { setSubmitting, resetForm }) => {
setSubmitting(true);
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
resetForm();
setSubmitting(false);
}, 100);
}}
//onSubmit={onSubmit}
>
{({
values,
errors,
status,
touched,
handleBlur,
handleChange,
isSubmitting,
setFieldValue,
handleSubmit,
props,
}) => (
<FormGroup>
<Form onSubmit={handleSubmit}>
<legend>
<strong>Create</strong> Tenant
</legend>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Show URL
</Label>
<Col md={7}>
<InputGroup>
<Field
id="appended-input"
name="domain_url"
type="text"
value={values.domain_url}
onSubmit={(values) => {
values.domain_url = values.domain_url + ".localhost";
}} //this isn't working
className={
"form-control" +
(errors.domain_url && touched.domain_url
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="domain_url"
component="div"
className="invalid-feedback"
/>
<InputGroupAddon addonType="append">
.localhost
</InputGroupAddon>
</InputGroup>
</Col>
</FormGroup>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Database Name
</Label>
<Col md={7}>
<Field
name="schema_name"
type="text"
className={
"form-control" +
(errors.schema_name && touched.schema_name
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="schema_name"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="normal-field" md={4} className="text-md-right">
Name
</Label>
<Col md={7}>
<Field
name="name"
type="text"
className={
"form-control" +
(errors.name && touched.name
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="name"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FieldArray
name="config"
render={(arrayHelpers) => (
<div>
{values.config.map((config, index) => (
<div key={index}>
<FormGroup row>
<Label
md={4}
className="text-md-right"
for="mask-date"
>
Tenant Description
</Label>
<Col md={7}>
<TextareaAutosize
rows={3}
name={`config.${index}.tenant_description`}
id="elastic-textarea"
type="text"
onReset={values.event_description}
placeholder="Quick description of tenant"
onChange={handleChange}
value={values.tenant_description}
onBlur={handleBlur}
className={
`form-control ${s.autogrow} transition-height` +
(errors.tenant_description &&
touched.tenant_description
? " is-invalid"
: "")
}
/>
<ErrorMessage
name="tenant_description"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
<FormGroup row>
<Label
for="normal-field"
md={4}
className="text-md-right"
>
Date
</Label>
<Col md={7}>
<DatePicker
tag={Field}
name={`config.${index}.date`}
type="date"
selected={values.date}
value={values.date}
className={
"form-control" +
(errors.date&& touched.date
? " is-invalid"
: "")
}
onChange={(e) =>
setFieldValue("date", e)
}
/>
<ErrorMessage
name="date"
component="div"
className="invalid-feedback"
/>
</Col>
</FormGroup>
</div>
))}
</div>
)}
/>
<div className="form-group">
<button
type="submit"
disabled={isSubmitting}
className="btn btn-primary mr-2"
>
Save Tenant
</button>
<button type="reset" className="btn btn-secondary">
Reset
</button>
</div>
</Form>
<Col md={7}>{JSON.stringify(values)}</Col>
</FormGroup>
)}
</Formik>
</div>
);
}
}
export default connect(null, { addTenant })(TenantForm);
You could use setFieldValue if you want to customize the value
https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void
You can add onChange
<Field
id="appended-input"
name="domain_url"
type="text"
value={values.domain_url}
onChange={st => {
let value = st.target.value;
let suffix = ".localhost";
let index = value.indexOf(".localhost");
if (index > 0) {
suffix = "";
}
//add suffix 'localhost' if it is not already added
props.setFieldValue("domain_url", value + suffix);
}}
className={
"form-control" +
(errors.domain_url && touched.domain_url ? " is-invalid" : "")
}
/>;
But adding suffix is more preferable on onSubmit:
onSubmit = {(values, actions) => {
console.log('valuesbefore',values)
values.domain_url= values.domain_url+ ".localhost"
console.log('valuesafter',values)
this.props.addTenant(values);
};
Related
i haven't work with rest api and formik so need guidance regarding that.
i have EDIT form where i have one user against id , i want to set user details on form and submit it with updated values and without any error if it kept unchanged.
for this i have to set values of Text Fields somehow and call patch api on submit
this is my form code :
<form onSubmit={handleSubmit}
>
<label className="userlabels">Username</label>
<TextField
name="userName"
placeholder="User Name"
type="text"
id="userName"
onBlur={handleBlur}
value={values.userName}
onChange={handleChange}
error={touched.userName && Boolean(errors.userName)}
helperText={touched.userName && errors.userName}
/>
<label className="userlabels">Fullname</label>
<TextField
name="fullName"
placeholder="Full Name"
type="text"
id="fullName"
onBlur={handleBlur}
value={values.fullName}
onChange={handleChange}
error={touched.fullName && Boolean(errors.fullName)}
helperText={touched.fullName && errors.fullName}
/>
<label className="userlabels">Email</label>
<TextField
name="email"
placeholder="Email"
type="email"
id="email"
onBlur={handleBlur}
value={values.email}
onChange={handleChange}
error={touched.email && Boolean(errors.email)}
helperText={touched.email && errors.email}
/>
<label className="userlabels">Password</label>
<TextField
sx={{
width: "55%",
marginBottom: "4vh",
}}
name="password"
placeholder="password"
type={passwordShown ? "text" : "password"}
id="password"
autoComplete="off"
onBlur={handleBlur}
value={values.password}
onChange={handleChange}
error={touched.password && Boolean(errors.password)}
helperText={touched.password && errors.password}
/>
<FormControl>
<label className="userlabels" id="role-label">
Role
</label>
<Select
name="role"
labelId="role-label"
id="role"
onChange={handleChange}
onBlur={handleBlur}
value={values.role}
error={touched.role && Boolean(errors.role)}
>
{role.map((option, index) => (
<MenuItem key={index} value={option.role}>
{option.role}
</MenuItem>
))}
</Select>
<FormHelperText error>
{touched.role && errors.role}
</FormHelperText>
</FormControl>
<label className="userlabels">Organization</label>
<TextField
sx={{
width: "55%",
marginBottom: "4vh",
}}
name="organ"
placeholder="Organization"
type="text"
id="organ"
onBlur={handleBlur}
value={[values.organ]}
onChange={handleChange}
error={touched.organ && Boolean(errors.organ)}
helperText={touched.organ && errors.organ}
/>
<FormControl>
<label className="userlabels" id="active-label">
Active
</label>
<Select
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
error={touched.active && Boolean(errors.active)}
>
{active.map((option, index) => (
<MenuItem key={index} value={option.id}>
{option.active}
</MenuItem>
))}
</Select>
<FormHelperText error>
{touched.active && errors.active}
</FormHelperText>
</FormControl>
<Button
variant="contained"
type="submit">
Update
</Button>
</form>
and this is formik code
const initialValues = {
fullName: "",
email: "",
userName: "",
organ: [] ,
password: "",
role: [],
active: "",
};
const { values, errors, touched, handleBlur, handleChange, handleSubmit } =
useFormik({
initialValues,
validationSchema: UserSchema,
onSubmit: (values, action) => {
fetch(`${state.baseUrl}/users/${id}`, {
method: "PATCH",
body: JSON.stringify({
fullname: values.fullName,
email: values.email,
username: values.userName,
organization: [values.organ],
password: values.password,
role: [values.role],
is_active: values.active,
}),
headers: {
"Content-type": "application/json",
},
})
.then((response) => {
if (response.status === 200) {
setAlert(true);
setMsg("You Are Successfully Updated the User");
setType("success");
return Promise.resolve();
} else {
setAlert(true);
setMsg("Some Thing Went Wrong , Please Try Again Later.");
setType("error");
return Promise.reject("failed");
}
})
.catch((error) => {
setAlert(true);
setMsg("Some Thing Went Wrong , Please Try Again Later.");
setType("error");
console.error("There was an error!", error);
});
action.resetForm();
},
});
i want to get pre-filled form and updated on submission
Hey guys ı have some issues react hook form handle submit function doesn't work what is issue can you help ?
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
return (
<Fragment>
<Card>
<CardHeader className='border-bottom'>
<CardTitle tag='h4'>İşletme Ayarları</CardTitle>
</CardHeader>
<CardBody className='py-2 my-25'>
<div className='d-flex'>
<div className='me-25'>
<img className='rounded me-50' alt='İşletmeye ait logo ' height='100' width='100' />
</div>
<div className='d-flex align-items-end mt-75 ms-1'>
<div>
<Button tag={Label} className='mb-75 me-75' size='sm' color='primary'>
Yükle
<Input type='file' hidden accept='image/*' />
</Button>
<Button className='mb-75' color='secondary' size='sm' outline >
Sil
</Button>
<p className='mb-0'> JPG veya PNG türünde yükleme yapınız</p>
</div>
</div>
</div>
<Form className='mt-2 pt-50' onSubmit={(e) => { e.preventDefault(); handleSubmit(onSubmit) }} >
<Row>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Ad Soyadı </Label>
<Input defaultValue={userDetail.name} {...register("name", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Kullanıcı adı </Label>
<Input defaultValue={userDetail.username} {...register("kullanici", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > E-mail </Label>
<Input type='email' defaultValue={userDetail.contact.email} {...register("email", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > İşletme Adı </Label>
<Input defaultValue={userDetail.companyName} {...register("companyName", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Telefon Numarası </Label>
<Cleave
value={userDetail.contact.phone}
{...register("phone", { required: true })}
className='form-control'
options={{ phone: true, phoneRegionCode: 'TR' }}
/>
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Adres</Label>
<Input defaultValue={userDetail.contact.address} {...register("address", { required: true })} />
</Col>
<Col className='mt-2' sm='12'>
<input type='submit' className='me-1' value='Kaydet' />
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Fragment>
)
}
export default AccountTabs
form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library, form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library,form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library
handleSubmit fires submit function only when validation is successful, So please see if all the required data is filled when you submit the form ( or handle the validations).
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit, formState } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
// formstate has the errors
console.log(formState.errors);
return (
<Fragment>
//code
</Fragment>
)
}
Check this link for validtions
Is there something wrong with the TextField component from Material UI that I'm missing?
My handleChange simply is not getting invoked.
I can type in value in the inputs, but state of the component is not changing.
Here is the Auth component:
const Auth = () => {
const [formData, setFormData] = useState(initialFormState)
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
}
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
})
}
return (
<Container component="main" maxWidth="xs">
<Paper className={classes.paper} elevation={3}>
<form className={classes.form} onSubmit={handleSubmit}>
<Grid container spacing={2}>
<Input name="email" label="e-mail" handleChange={handleChange} type="email" />
<Input name="password" label="password" handleChange={handleChange} type={showPassword ? "text" : "password"} handleShowPassword={handleShowPassword} />
</Grid>
<Button type="submit" variant="contained" color="primary" className={classes.submit} fullWidth>
{isSignup ? "Sign up" : "Sign in"}
</Button>
</form>
</Paper>
</Container>
);
}
And the input component which is inside Auth:
const Input = ({ name, half, handleChange, type, label, autoFocus, handleShowPassword }) => {
return (
<>
<Grid item xs={12} sm={half ? 6 : 12}>
<TextField
name={name}
handleChange={handleChange}
variant="outlined"
required
fullWidth
label={label}
autoFocus={autoFocus}
type={type}
InputProps={name === "password" ? {
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={handleShowPassword}>
{type === "password" ? <Visibility/> : <VisibilityOff/>}
</IconButton>
</InputAdornment>
)
} : null}
/>
</Grid>
</>
);
}
You've to change the input attribute from handleChange to onChange
<Input name="email" label="e-mail" onChange={handleChange} type="email" />
<Input name="password" label="password" onChange={handleChange} type={showPassword ? "text" : "password"} handleShowPassword={handleShowPassword} />
I have a multistep form for signing up. What is the easiest and the best approach for form validation? What should I use? Is it alright to use Formik for that? Could you suggest to me what to do?
Here is one of the forms:
return(
<Container>
<Row className="justify-content-center">
<Col md="8">
<Card border="dark">
<Card.Title className="text-center">New User</Card.Title>
<Card.Body>
<Form>
<Form.Group controlId="formGridFirstName">
<Form.Label>First Name</Form.Label>
<Form.Control type="text" value={formValues.firstName} onChange={handleChange('firstName')} />
</Form.Group>
<Form.Group controlID="formGridLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" value={formValues.lastName} onChange={handleChange('lastName')} />
</Form.Group>
<Form.Group controlID="formGridEmail">
<Form.Label>Email</Form.Label>
<Form.Control type="email" value={formValues.email} onChange={handleChange('email')} />
</Form.Group>
<Form.Group controlId="formGridPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" value={formValues.password} onChange={handleChange('password')} />
</Form.Group>
<Form.Group controlId="formGridPhone">
<Form.Label>Phone</Form.Label>
<Form.Control type="tel" value={formValues.phone} onChange={handleChange('phone')} />
</Form.Group>
<Button variant="light" type="submit" size="lg" onClick={redirectToHome}>Cancel</Button>
<Button variant="primary" type="submit" size="lg" onClick={saveAndContinue}>Next</Button>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
};
You can use Formik and a Yup for validation schema:
https://formik.org/docs/api/formik#validationschema-schema----schema
npm links:
https://www.npmjs.com/package/formik
https://www.npmjs.com/package/yup
It will look like this:
export default function MyForm() {
const initValues = {
firstName: "",
lastName: "",
email: "",
password: "",
phone: ""
};
const schema = Yup.object().shape({
firstName: Yup.string(),
lastName: Yup.string(),
email: Yup.string().email("Email format is invalid."),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/[a-zA-Z]/, "Password can only contain Latin letters."),
phone: Yup.string().phone(" ")
});
return (
<Formik validationSchema={schema} initialValues={initValues}>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
setFieldTouched
} = props;
return (
<Container>
<Row className="justify-content-center">
<Col md="8">
<Card border="dark">
<Card.Title className="text-center">New User</Card.Title>
<Card.Body>
<Form>
<Form.Group controlId="formGridFirstName">
<Form.Label>First Name</Form.Label>
<Form.Control
name="firstName"
type="text"
value={values.firstName}
onChange={handleChange}
setFieldTouched={setFieldTouched}
errors={errors}
/>
</Form.Group>
<Form.Group controlID="formGridLastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
name="lastName"
type="text"
value={values.lastName}
onChange={handleChange}
setFieldTouched={setFieldTouched}
errors={errors}
/>
</Form.Group>
<Form.Group controlID="formGridEmail">
<Form.Label>Email</Form.Label>
<Form.Control
name="email"
type="email"
value={values.email}
onChange={handleChange}
setFieldTouched={setFieldTouched}
errors={errors}
/>
</Form.Group>
<Form.Group controlId="formGridPassword">
<Form.Label>Password</Form.Label>
<Form.Control
name="password"
type="password"
value={values.password}
onChange={handleChange}
setFieldTouched={setFieldTouched}
errors={errors}
/>
</Form.Group>
<Form.Group controlId="formGridPhone">
<Form.Label>Phone</Form.Label>
<Form.Control
name="phone"
type="tel"
value={values.phone}
onChange={handleChange}
setFieldTouched={setFieldTouched}
errors={errors}
/>
</Form.Group>
<Button
variant="light"
type="submit"
size="lg"
onClick={redirectToHome}
>
Cancel
</Button>
<Button
variant="primary"
type="submit"
size="lg"
onClick={saveAndContinue}
>
Next
</Button>
</Form>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
}}
</Formik>
);
}
But you should change also your Form.Control component:
Add
import { ErrorMessage, getIn } from "formik";
const error = getIn(props.errors, props.name);
and add to your Input these attributes
onChange={(e) => {setFieldTouched("firstName");handleChange(e);}
error={error}
and Error to show
<Error component="div" name={props.name} />
I would suggest adding your own validators and bundling inputs that are of the same type. For example First Name and Last Name are both strings so you can have a validator for string types. You could do it like this
//validator.js
const stringValidator = (value) => {
if(isEmpty(value)){
return { isValid: false, errors: ["Field cannot be blank"] }
}
return { isValid: true, errors: [] }
}
const config = {
firstName: stringValidator,
lastName: stringValidator,
email: emailValidator,
cellphone: cellphoneValidator,
password: passwordValidator
}
const getValidator = (questionId) => config[questionId];
export default (questionId, value) => {
const validate = getValidator(questionId);
return validate(value)
}
...
// Form.js class
answerQuestion(questionId){
return (e) => {
const answer = e.target.value;
const validation = validate(questionId, answer)
const { errors } = validation;
let { fields } = this.state;
fields[questionId] = { errors, value, label: field.label }
this.setState({ fields })
}
}
...
<Form>
{this.state.fields.map( field => {
return(
<Form.Group>
<Form.Label>{field.label}</Form.Label>
<Form.Control type="text" value={field.value} onChange={this.answerQuestion(field.questionId)} />
{field.errors.map(err => <span>{err}</span>}
</Form.Group>
)
}
</Form>
I'm trying to get the currently logged in users email and use it in my fetch() call. I can currently get the email from getfirstapi() and use it in my form but I'm having trouble passing it into my getSecondApi() where the fetch() is ?
Iv tried creating a getEmail function to return it, but with no luck.
Code
import * as React from "react";
import axios from "axios";
import { Form, Card, Grid } from "tabler-react";
import { Button, Modal } from "semantic-ui-react";
import Auth from '#aws-amplify/auth';
import '../../index.css';
import { arrayOf } from "prop-types";
//const config = require('../config.json');
class GeneralInformation extends React.Component {
constructor(props) {
super(props);
this.state = {
// States from API
firstname: "",
middlename: "",
surname: "",
city: "",
postcode: "",
state: "",
email: "",
about: "",
// States for editable form
formfirstname: "",
formmiddlename: "",
formsurname: "",
formcity: "",
formpostcode: "",
formstate: "",
formabout: "",
// Modal State
open: false,
};
}
getUseremail() {
return Auth.currentAuthenticatedUser().then(user => user.attributes.email)
}
email = Auth.currentAuthenticatedUser().then(user => user.attributes.email)
getFirstApi() {
return Auth.currentAuthenticatedUser().then((user) => {
this.setState({email: user.attributes.email, formemail: user.attributes.email})
});
}
getSecondApi(email) {
fetch(`https://ezha2ns0bl.execute-api.ap-southeast-2.amazonaws.com/prod/userdata?foo=${encodeURIComponent(email)}`)
.then(res => res.json())
.then(
console.log("THIS IS RESULT2 " + email),
(result) => {
this.setState({
firstname: result.Item.userFirstName,
middlename: result.Item.userMiddleName,
surname: result.Item.userLastName,
city: result.Item.userCity,
postcode: result.Item.userPostcode,
state: result.Item.userState,
about: result.Item.userAbout,
formfirstname: result.Item.userFirstName,
formmiddlename: result.Item.userMiddleName,
formsurname: result.Item.userLastName,
formcity: result.Item.userCity,
formpostcode: result.postcode,
formstate: result.Item.userState,
formabout: result.Item.userAbout,
});
console.log("THIS IS RESULT1 " + result)} ,
)
}
componentDidMount() {
this.getFirstApi();
this.getSecondApi();
}
handleChange = (input) => (event) => {
this.setState({ [input]: event.target.value });
};
handleSubmit = async (event) => {
event.preventDefault();
this.setState((prevState) => ({
// If submitting new values, update the state to represent the new data
firstname: prevState.formfirstname,
middlename: prevState.formmiddlename,
surname: prevState.formsurname,
city: prevState.formcity,
postcode: prevState.formpostcode,
email: prevState.formemail,
userState: prevState.formstate,
about: prevState.formabout,
open: false,
}))
try {
const params = {
"userFirstName": this.state.formfirstname,
"userMiddleName": this.state.formmiddlename,
"userLastName": this.state.formsurname,
"userCity": this.state.formcity,
"userPostCode": this.state.formpostcode,
"userEmail": this.state.formemail,
"userState": this.state.formstate,
"userAbout": this.state.formabout,
"userType": "jobseeker"
};
await axios.post('https://qrg3idkox4.execute-api.ap-southeast-2.amazonaws.com/prod/{userEmail}/', params);
}catch (err) {
console.log(`An error has occurred: ${err}`);
}
};
cancelForm = () => {
// If cancelling, reset any fields that have been changed to the original values so that when the modal is re-opened, the old values are shown
this.setState((prevState) => ({
formfirstname: prevState.firstname,
formmiddlename: prevState.middlename,
formsurname: prevState.surname,
formcity: prevState.city,
formpostcode: prevState.postcode,
formstate: prevState.state,
formabout: prevState.about,
open: false,
}));
};
openModal = () => {
this.setState({ open: true });
};
render() {
const {
firstname,
middlename,
surname,
city,
postcode,
state,
email,
about,
formfirstname,
formmiddlename,
formsurname,
formcity,
formpostcode,
formstate,
formabout,
open,
} = this.state;
return (
<div className="card" name="generalInfo">
<Card.Body>
<Grid>
<Grid.Row>
<Grid.Col md={7}>
<Card.Title>General Information</Card.Title>
</Grid.Col>
<Grid.Col md={5}>
{/* MODAL BUTTON */}
<Button
floated="right"
basic
icon="pencil"
type="button"
compact
onClick={this.openModal}
/>
</Grid.Col>
</Grid.Row>
<Grid.Row>
{/* ROW 1 */}
<Grid.Col md={4}>
<Form.Group label="First Name">
<Form.Input name="firstname" readOnly value={firstname} />
</Form.Group>
</Grid.Col>
<Grid.Col md={4}>
<Form.Group label="Middle Name">
<Form.Input name="middlename" readOnly value={middlename} />
</Form.Group>
</Grid.Col>
<Grid.Col md={4}>
<Form.Group label="Surname">
<Form.Input name="surname" readOnly value={surname} />
</Form.Group>
</Grid.Col>
{/* ROW 2 */}
<Grid.Col md={3}>
<Form.Group label="City">
<Form.Input name="city" readOnly value={city} />
</Form.Group>
</Grid.Col>
<Grid.Col md={2}>
<Form.Group label="Post Code">
<Form.Input name="postcode" readOnly value={postcode} />
</Form.Group>
</Grid.Col>
<Grid.Col md={3}>
<Form.Group label="State">
<Form.Input name="state" readOnly value={state} />
</Form.Group>
</Grid.Col>
<Grid.Col md={4}>
<Form.Group label="Email">
<Form.Input name="email" readOnly value={email} />
</Form.Group>
</Grid.Col>
{/* ROW 3 */}
<Grid.Col md={12}>
<Form.Group className="mb=0" label="About Me">
<Form.Textarea
name="aboutme"
rows={3}
disabled
readOnly
value={about}
/>
</Form.Group>
</Grid.Col>
</Grid.Row>
</Grid>
</Card.Body>
{/* MODAL CONTENT */}
<Modal
style={{ position: "relative" }}
closeOnDimmerClick={false}
open={open}
>
<Modal.Header>Edit Info</Modal.Header>
<Modal.Content>
<Form onSubmit={this.handleSubmit}>
<Grid.Row>
<Grid.Col md={4}>
<Form.Group label="First Name">
<Form.Input
name="firstname"
value={formfirstname}
onChange={this.handleChange("formfirstname")}
/>
</Form.Group>
</Grid.Col>
<Grid.Col md={4}>
<Form.Group label="Middle Name">
<Form.Input
name="middlename"
value={formmiddlename}
onChange={this.handleChange("formmiddlename")}
/>
</Form.Group>
</Grid.Col>
<Grid.Col md={4}>
<Form.Group label="Surname">
<Form.Input
name="surname"
value={formsurname}
onChange={this.handleChange("formsurname")}
/>
</Form.Group>
</Grid.Col>
</Grid.Row>
{/* ROW 2 */}
<Grid.Row>
<Grid.Col md={3}>
<Form.Group label="City">
<Form.Input
name="city"
value={formcity}
onChange={this.handleChange("formcity")}
/>
</Form.Group>
</Grid.Col>
<Grid.Col md={2}>
<Form.Group label="Post Code">
<Form.Input
name="postcode"
value={formpostcode}
onChange={this.handleChange("formpostcode")}
/>
</Form.Group>
</Grid.Col>
<Grid.Col md={3}>
<Form.Group label="State">
<Form.Input
name="state"
value={formstate}
onChange={this.handleChange("formstate")}
/>
</Form.Group>
</Grid.Col>
</Grid.Row>
{/* ROW 3 */}
<Grid.Row>
<Grid.Col md={12}>
<Form.Group className="mb=0" label="About Me">
<Form.Textarea
name="aboutme"
rows={3}
value={formabout}
onChange={this.handleChange("formabout")}
/>
</Form.Group>
</Grid.Col>
</Grid.Row>
{/* ROW 4 - SUBMIT */}
<Grid.Row>
<Grid.Col md={12}>
<Button
floated="left"
basic
type="button"
color="red"
onClick={this.cancelForm}
>
{" "}
Cancel{" "}
</Button>
<Button floated="right" basic type="submit" color="green">
{" "}
Accept Changes{" "}
</Button>
</Grid.Col>
</Grid.Row>
</Form>
</Modal.Content>
</Modal>
</div>
);
}
}
export default GeneralInformation;
Form
EDIT
> getEmailApi() { return
> Auth.currentAuthenticatedUser().then((user) => {
> const { attributes = {} } = user;
> console.log(attributes['email']);
> })}
iv created this function to get the email
but don't know how to pass it into the getSecondApi
My Solution
getEmailApi() {
return Auth.currentAuthenticatedUser().then((user) => {
const { attributes = {} } = user;
console.log(attributes['email']);
let email = attributes['email']
return email
})}
getFirstApi() {
return Auth.currentAuthenticatedUser().then((user) => {
this.setState({email: user.attributes.email, formemail: user.attributes.email})
});
}
getSecondApi(email) {
fetch(`https://ezha2ns0bl.execute-api.ap-southeast-2.amazonaws.com/prod/userdata?userEmail=${encodeURIComponent(email)}`)
.then(res => res.json())
.then(
console.log("THIS IS RESULT2 " + email),
(result) => {
this.setState({
firstname: result.Item.userFirstName,
middlename: result.Item.userMiddleName,
surname: result.Item.userLastName,
city: result.Item.userCity,
postcode: result.Item.userPostcode,
state: result.Item.userState,
about: result.Item.userAbout,
formfirstname: result.Item.userFirstName,
formmiddlename: result.Item.userMiddleName,
formsurname: result.Item.userLastName,
formcity: result.Item.userCity,
formpostcode: result.postcode,
formstate: result.Item.userState,
formabout: result.Item.userAbout,
});
console.log("THIS IS RESULT1 " + result)} ,
)
}
BeforDidMount() {
this.getEmailApi().then(email => this.getSecondApi(email)); }
componentDidMount() {
this.BeforDidMount();
this.getFirstApi();
}