How to make modal appear onClick change? - javascript

I am stuck on getting my Modal to appear when the Edit button is clicked. I can see that the modalShow is being set to true when I click the button since I console.log the value. Any idea on how to get modal to appear when user clicks the edit button?
product-screen.jsx
import { useState } from 'react';
import { Button, Card, Form, Modal } from 'react-bootstrap';
import 'reactjs-popup/dist/index.css';
import ModalScreen from './modal-screen';
const ProductCardScreen = ({ product }) => {
const { productName, productPrice, productInStock, productDescription } =
product;
const [modalShow, setModalShow] = useState(false);
const [updateProduct, setProductUpdate] = useState({
productDescription,
productInStock,
productName,
productPrice,
});
const handleChange = (event) => {
console.log('event', event.target.value);
setProductUpdate({
...updateProduct,
[event.target.name]: event.target.value,
});
};
// todo
const saveUpdatedProduct = (product) => {
// save logic here to db
};
const handleDelete = () => {
alert('Are you sure you want to delete?');
};
const handleModalChange = () => {
console.log('called');
setModalShow(true);
};
return (
<div>
<Card>
<Card.Body>
<Card.Title>Product Name: {product.productName}</Card.Title>
<Card.Text>
Product Description: {product.productDescription}
</Card.Text>
<Card.Text>Product Quantity: {product.productInStock}</Card.Text>
<Card.Text>Price: ${product.productPrice}</Card.Text>
<div
style={{
float: 'right',
}}
>
<Button
style={{ margin: '10px' }}
onClick={() => handleModalChange()}
className='btn btn-primary'
variant='primary'
>
Edit
</Button>
<Button
onClick={() => handleDelete()}
className='btn btn-danger'
variant='primary'
>
Delete
</Button>
</div>
</Card.Body>
</Card>
<ModalScreen product={product} handleChange={handleChange} />
</div>
);
};
export default ProductCardScreen;
modal-screen.jsx
import { Button, Form, Modal } from 'react-bootstrap';
const ModalScreen = ({ product, handleChange }) => {
const { productName, productPrice, productInStock, productDescription } =
product;
return (
<Modal
animation={false}
size='lg'
aria-labelledby='contained-modal-title-vcenter'
centered
>
<Modal.Header>
<Modal.Title id='contained-modal-title-vcenter'>
Product Information
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group className='mb-3'>
<Form.Label>Name</Form.Label>
<Form.Control
onChange={handleChange}
value={productName}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Description</Form.Label>
<Form.Control
onChange={handleChange}
value={productDescription}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Amount In Stock</Form.Label>
<Form.Control
onChange={handleChange}
value={productInStock}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Price</Form.Label>
<Form.Control
onChange={handleChange}
value={`$${productPrice}`}
type='text'
/>
</Form.Group>
<Button variant='primary' type='button'>
Save
</Button>
<Button variant='danger' type='button'>
Cancel
</Button>
</Form>
</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
);
};
export default ModalScreen;

Related

UI Table of Data not updating after useMutation Update/Edit data

Description
i'm working on reactjs and apollo client project. i'm also developing editUser feature. edit mutation is working but table UI data not update. i want to update data in the table after Edit Mutation.
Problem
So here , im edit this user data.
into this.
when i'm click "submit" the data is still not update UI.
but when i'm refreshing the page
the data shows correctly edit and changed.
Code
ModalEdit.js
import React, { useEffect, useState } from "react";
import { useQuery, useMutation } from "#apollo/client";
import { Button, Modal, Form } from "react-bootstrap";
import { GET_ALL_USERS, GET_USER_BY_ID } from "../../../gql/query";
import { UPDATE_USER } from "../../../gql/mutation";
const ModalEdit = ({ show, onClose, username }) => {
// state for check input component
const [isChecked, setIsChecked] = useState("ACTIVE");
// state for input values
const [value, setValue] = useState({
group_id: "",
full_name: "",
email: "",
phone: "",
address: "",
password: "",
});
useEffect(() => {
if (show) {
document.body.classList.add("modal-open");
}
return () => {
if (document.body.classList.contains("modal-open")) {
document.body.classList.remove("modal-open");
}
};
}, [show]);
const { data, loading, error, refetch } = useQuery(GET_USER_BY_ID, {
variables: { username: username },
});
const [updateUser, { error: updateError, loading: updateLoading }] =
useMutation(UPDATE_USER, {
onCompleted: () => {
refetch();
onClose();
},
onError: (err) => {
console.error(JSON.stringify(err, null, 2));
},
});
const dataUser = data?.getUserByID;
useEffect(() => {
if (dataUser) {
setValue({
group_id: dataUser.group_id,
full_name: dataUser.full_name,
email: dataUser.email,
phone: dataUser.phone,
address: dataUser.address,
password: dataUser.password,
});
}
}, [dataUser]);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
const handleChange = (event) => {
setValue({ ...value, [event.target.name]: event.target.value });
};
// handle mutation for edit user
const handleSubmit = (event) => {
event.preventDefault();
updateUser({
variables: {
username: username,
input: {
group_id: value.group_id,
full_name: value.full_name,
email: value.email,
phone: value.phone,
address: value.address,
password: value.password,
},
}
});
};
return (
<Modal show={show}>
<Modal.Header>
<Modal.Title>
{" "}
<span>FORMULIR AKUN PENGGUNA</span>{" "}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Role Akun</Form.Label>
<Form.Select
aria-label="pilih user role"
name="group_id"
onChange={handleChange}
>
<option value={value.group_id}>{value.group_id}</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Nama Lengkap</Form.Label>
<Form.Control
type="text"
name="full_name"
value={value.full_name}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
name="email"
value={value.email}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Phone</Form.Label>
<Form.Control
type="text"
name="phone"
value={value.phone}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
value={value.password}
onChange={handleChange}
/>
</Form.Group>
<Form.Label>Aktifkan Akun</Form.Label>
{dataUser.status === "ACTIVE" ? (
<Form.Check
type="switch"
checked={isChecked}
onChange={(event) => setIsChecked(event.target.checked)}
id="custom-switch"
label="Aktifkan Akun"
/>
) : (
<Form.Check
type="switch"
id="custom-switch"
checked={isChecked}
onChange={(event) => setIsChecked(event.target.checked)}
label="Aktifkan Akun"
/>
)}
<Form.Group className="d-flex">
<Button variant="primary" type="submit">
Submit
</Button>
<Button variant="secondary" onClick={onClose}>
Close
</Button>
</Form.Group>
</Form>
</Modal.Body>
</Modal>
);
};
export default ModalEdit;
Table.js (Modal Edit Triggerred From Here)
<Table responsive>
<thead>
<tr>
<th>No</th>
<th>Nama Pengguna</th>
<th>Role Akun</th>
<th>Email</th>
<th>Tanggal Daftar</th>
<th>Status Akun</th>
<th>Pengaturan</th>
</tr>
</thead>
<tbody>
{data.getAllUsers.rows.map((user, index) => (
<tr key={user.username}>
<td>{index + 1}</td>
<td>{user.full_name}</td>
<td>{user.group_id}</td>
<td>{user.email}</td>
<td>{user.created_dtm}</td>
<td>{user.status}</td>
<td>
{user.status !== "ACTIVE"
? [
<Button
key="Aktifkan Akun"
className="d-block mb-2 text-white bg-secondary w-100"
>
Aktifkan Akun
</Button>,
<Button
key="Ganti Role Akun"
className="d-block mb-2 btn-block btn-sm w-100"
disabled
>
Ganti Role Akun
</Button>,
]
: user.group_id === "admin"
? [
<Button
key="Ganti Role Akun"
variant="outline-success"
className="d-block btn-sm mb-2 w-100"
>
Ganti Role Akun
</Button>,
]
: [
<Button
key="Pilih Role Akun"
className="d-block btn-sm mb-2 w-100"
>
Pilih Role Akun
</Button>,
]}
<Button
key="Edit"
variant="outline-primary"
onClick={() => {
setShowModal(true);
setUsername(user.username);
}}
className="d-block btn-block btn-sm mb-2 w-100"
>
Edit
</Button>
<Button
key="Hapus"
variant="outline-danger"
onClick={() => {
handleDelete(user.username)
}}
disabled={loading}
className="d-block btn-block btn-sm mb-2 w-100"
>
Hapus
</Button>
</td>
</tr>
))}
</tbody>
{showModal ? (
<ModalEdit
show={handleShowModal}
onClose={handleCloseModal}
username={username}
/>
) : null}
</Table>
Question
How to make the UI change after Edit Mutation ?
Any help will be appreciated , Thankyou

Modal not popping up at react and sends to an empty page after click of a button

Hello on ReactJS Bootstrap. When I try to click my button for the handleShow of the Modal
It sends me to a blank webpage and just get's stuck there. I tried to debug and my state show changes to true but it never shows the modal.
added text since stack overflow does not want me to post if the wording is not a lot, added text since stack overflow does not want me to post, added text since stack overflow does not want me to post
Any help would be appreciated.
Thanks!
import React, { Component, useState } from "react";
import Modal from "react-bootstrap/Modal";
import { useHistory } from "react-router-dom";
import Axios from "axios";
// import Profile from '../pages/forms';
import { Link } from "react-router-dom";
import Form from "react-bootstrap/Form";
import "../index.css";
import { setGlobalState, useGlobalState } from "../globals/globalVar";
function LoginComponent(props) {
// const
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [show, setShow] = useState(false);
const history = useHistory();
// make an axios query
const url = useGlobalState("defaultUrl");
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleEmailAndpasswordVerify = () => {
if (email.length === 0) {
alert("Email cannot be empty.");
return -1;
}
// email must contain #csub.edu
if (!email.includes("#csub.edu")) {
alert("Email must contain #csub.edu");
return -1;
}
// if the len of password is less than 8 then reject
if (password.length < 8) {
alert("Password must be at least 8 characters long.");
return -1;
}
return 0;
};
const handleSubmit = (e) => {
if (handleEmailAndpasswordVerify() !== 0) {
// if the email and password are valid then send the request to the server
// to register
// send the request to the server
// if success then close the modal
// if fail then alert the error
return;
}
e.preventDefault();
// make a post axios request to a server
Axios.post("http://localhost:8000/index.php", {
email: email,
password: password,
}).then((response) => {
if (response.data.message) {
console.log(response.data);
// console.log(loginStatus);
} else {
// alert the error
alert(response.data.error);
// history.push("/main");
}
});
setShow(false);
};
const login = () => {
Axios.post(url, {
email: email,
password: password,
}).then((response) => {
if (response.data.message) {
console.log(response.data);
// console.log(loginStatus);
} else {
// setLoginStatus(response.data[0].username);
history.push("/main");
}
});
};
//login validator
const loginValidate = () => {
if (email.length === 0) {
alert("Username cannot be empty.");
return;
}
if (password.length === 0) {
alert("Password cannot be empty.");
return;
}
login();
};
return (
<div>
<form>
<nav className="navbar navbar-expand-lg navbar-light fixed-top">
<div className="container">
<Link className="navbar-brand fs-1"> StuHuB </Link>{" "}
<div
className="collapse navbar-collapse"
id="navbarTogglerDemo02"
></div>{" "}
</div>{" "}
</nav>{" "}
<div className="auth-wrapper">
<div className="auth-inner">
<h3> Sign In </h3>{" "}
<div className="form-group">
<label> Login ID </label>{" "}
<input
type="text"
className="form-control"
placeholder="Enter Login ID"
onChange={(e) => {
setEmail(e.target.value);
}}
/>{" "}
</div>{" "}
<div className="form-group">
<label> Password </label>{" "}
<input
type="password"
className="form-control"
placeholder="Enter password"
onChange={(e) => {
setPassword(e.target.value);
}}
/>{" "}
</div>{" "}
<button
onClick={loginValidate}
type="button"
className="btn btn-primary btn-block"
>
Submit{" "}
</button>{" "}
</div>{" "}
<button className="btn btn-primary btn-block" onClick={handleShow}>
Register
</button>
</div>{" "}
</form>
{/* Not working? */}
{/* Modal */}
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
<Form.Label>Email address</Form.Label>
<Form.Control
type="email"
placeholder="name#example.com"
autoFocus
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
{/* form password */}
<Form.Item
name="password"
label="Password"
rules={[
{
required: true,
message: "Please enter password!",
},
]}
>
<input
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Item>
</Form>
</Modal.Body>
<Modal.Footer>
<button variant="secondary" onClick={handleClose}>
Close
</button>
<button variant="primary" onClick={handleSubmit}>
Submit
</button>
</Modal.Footer>
</Modal>
{/* make a hidden modal */}
</div>
);
}
export default LoginComponent;

Multiple Modal Opening when Updating a Row using React

I created a project using React and Bootstrap Table. Opening of modal is functional but unfortunately all the data in the table also opens their own modal.
So example I have 5 data in the table, when updating a row, the other four (4) modal also rendered and display.
The id of the data from Firestore is accessible to the child component (Edit_Modal.tsx) is there a way to add an id for the modal to make a reference to the data?
Manuscript.jsx
<tbody>
{thesisData.map((doc, index) => {
return (
<tr key={doc.id}>
<td>{index + 1}</td>
<td>{doc.title}</td>
<td>
{doc.members[0]}, {doc?.members[1]}
</td>
<td>{doc.adviser}</td>
<td>{doc.course}</td>
<td>{doc.pages}</td>
<td className="m-1 text-center">
<Button
className="mb-1"
variant="secondary"
onClick={(e) => openUpdateModal(doc.id, e)}
>
<IconContext.Provider value={{ color: "#fff" }}>
<div>
<BsFillPencilFill />
</div>
</IconContext.Provider>
{showModalEdit && <Edit_Modal modalToggle={doc.id} />}
</Button>
<Button
className="mb-1"
variant="danger"
onClick={(e) => deleteHandler(doc.id)}
>
<IconContext.Provider value={{ color: "#fff" }}>
<div>
<BsFillTrashFill />
</div>
</IconContext.Provider>
</Button>
</td>
</tr>
);
})}
</tbody>
openUpdateModal() function
const openUpdateModal = (id) => {
setThesisId(id);
setShowModalEdit(true);
};
Edit_Modal.tsx
const Edit_Modal = ({ modalToggle }) => {
//Use States for Modal
const [show, setShow] = useState(true);
const handleClose = () => {
setShow(!show);
};
return ReactDom.createPortal(
<div>
<Modal
show={show}
keyboard={false}
onHide={handleClose}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Update Thesis Details
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form
noValidate
validated={validated}
id="addFormId"
onSubmit={handleUpdateForm}
>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridTitle">
<Form.Label>Title</Form.Label>
<Form.Control
type="text"
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter title"
value={title}
required
/>
<Form.Control.Feedback type="invalid">
Please enter a title.
</Form.Control.Feedback>
</Form.Group>
<Form.Group as={Col} controlId="formGridAdviser">
<Form.Label>Adviser</Form.Label>
<Form.Control
type="text"
onChange={(e) => setAdviser(e.target.value)}
placeholder="Name of Adviser"
value={adviser}
required
/>
<Form.Control.Feedback type="invalid">
Please enter an Adviser.
</Form.Control.Feedback>
</Form.Group>
</Row>
<Form.Group className="mb-3" controlId="formGridAbstract">
<Form.Label>Abstract</Form.Label>
<Form.Control
as="textarea"
onChange={(e) => setAbstract(e.target.value)}
rows={3}
placeholder="Enter Abstract Details"
value={abstract}
required
/>
<Form.Control.Feedback type="invalid">
Please enter Abstract Details.
</Form.Control.Feedback>
</Form.Group>
<Button type="Submit">Add Content</Button>
</Form>
</Modal.Body>
</Modal>
</div>,
document.getElementById("modal-root")
);
};
export default Edit_Modal;
As #adhinarayan said you can use the useState of setThesisId to get the specific ID of your document.
Example useState:
const [thesisId, setThesisId] = useState("");
You can use the openUpdateModal function to get the Modal and the thesis ID
const openUpdateModal = (id) => {
setThesisId(id); //useState for ID
setShowModalEdit(true); //useState for Modal
};
Finally, make sure that the Modal Component was placed outside of the map function to avoid looping of modals. You can set the thesisId to customized props of Edit_Modal
...</tbody>
</Table>
{showModalEdit && <Edit_Modal modalToggle={thesisId} />}
</Col>...

How to clear react-select value after formik form submission?

I have a formik form where I have used react-select for select list. Here is my form:
import React from "react";
import { ErrorMessage, Field, Form, Formik } from "formik";
import * as Yup from "yup";
import { Button, Col, FormGroup } from "reactstrap";
import Select from "react-select";
const AddBankForm = (props) => {
return (
<Formik
initialValues={{
district: props.districts,
}}
validationSchema={Yup.object({
district: Yup.string().required("Required"),
})}
onSubmit={(values, actions) => {
setError(null);
setMessage(null);
try {
const response = await postDataWithAuth(DISTRIBUTOR_BANK_ADD, {
routing_number: values.branch,
bank_account_number: values.accountNumber,
account_holder_name: values.accountName,
pin_number: values.tpin,
});
// This is not working
actions.resetForm();
setMessage(response.message);
} catch (e) {
setError(e.response.data);
}
actions.setSubmitting(false);
}}
>
{(formikProps) => (
<Form onSubmit={formikProps.handleSubmit} autoComplete="one-time-code">
<div className="form-row">
<Col>
<FormGroup>
<label>
District<span className="text-danger">*</span>
</label>
<Select
menuPortalTarget={document.body}
type="text"
name="district"
onChange={(option) => {
props.updateDistrict(option.value);
formikProps.setFieldValue("district", option.value);
}}
options={
props.isCreateLiftingSuccessful ? [] : props.districts
}
onBlur={formikProps.handleBlur}
/>
<ErrorMessage
name="district"
component="div"
className="text-danger"
/>
</FormGroup>
</Col>
</div>
<div className="form-row mt-3 text-center">
<Col>
<Button
className="btn btn-success"
type="submit"
disabled={!formikProps.dirty || formikProps.isSubmitting}
>
Submit
</Button>
</Col>
</div>
</Form>
)}
</Formik>
);
};
The problem is that the react-select field is not getting cleared after the form submission. I have used formik's resetForm() method to clear my form. But it seems that resetForm method does not have any impact on the react-select field.
You can use 'ref' props for clear react-select field.
import React from "react";
import { ErrorMessage, Field, Form, Formik } from "formik";
import * as Yup from "yup";
import { Button, Col, FormGroup } from "reactstrap";
import Select from "react-select";
const AddBankForm = (props) => {
// update start
let selectRef = null;
const clearValue = () => {
selectRef.select.clearValue();
};
// update end
return (
<Formik
initialValues={{
district: props.districts,
}}
validationSchema={Yup.object({
district: Yup.string().required("Required"),
})}
onSubmit={(values, actions) => {
setError(null);
setMessage(null);
try {
const response = await postDataWithAuth(DISTRIBUTOR_BANK_ADD, {
routing_number: values.branch,
bank_account_number: values.accountNumber,
account_holder_name: values.accountName,
pin_number: values.tpin,
});
// This is not working
actions.resetForm();
// Try this way
clearValue();
setMessage(response.message);
} catch (e) {
setError(e.response.data);
}
actions.setSubmitting(false);
}}
>
{(formikProps) => (
<Form onSubmit={formikProps.handleSubmit} autoComplete="one-time-code">
<div className="form-row">
<Col>
<FormGroup>
<label>
District<span className="text-danger">*</span>
</label>
<Select
// use ref
ref={ref => {
selectRef = ref;
}}
menuPortalTarget={document.body}
type="text"
name="district"
onChange={(option) => {
props.updateDistrict(option.value);
formikProps.setFieldValue("district", option.value);
}}
options={
props.isCreateLiftingSuccessful ? [] : props.districts
}
onBlur={formikProps.handleBlur}
/>
<ErrorMessage
name="district"
component="div"
className="text-danger"
/>
</FormGroup>
</Col>
</div>
<div className="form-row mt-3 text-center">
<Col>
<Button
className="btn btn-success"
type="submit"
disabled={!formikProps.dirty || formikProps.isSubmitting}
>
Submit
</Button>
</Col>
</div>
</Form>
)}
</Formik>
);
};

reactjs fetch with parameters from cognito

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

Categories