How to pass value of inputs to other function? - javascript

I create multiple step button with useState hook and it work fine. Now I trying pass value of inputs from step two of button to step three. There is a problem I can't pass props or state in my function and I have error that state or props is undefined. I try more and more but give nothing.
This is my code :
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview, setShowPreview] = useState(false);
const [formHidden, setFormHidden] = useState(false);
return (
<div className="col-12">
{!showForm ? (
<ShowFormButton onClick={() => setShowForm(true)}/>
) : undefined}
{showForm ? (
<div className={''} id="scrollbar-style">
<div>
<HideFormButton
onClick={() => {
setShowForm(false);
}}
/>
</div>
{!formHidden ? <MyForm/> : undefined}
{!showPreview ? (
<ShowPreviewButton
onClick={() => {
setShowPreview(true);
setFormHidden(true);
}}
/>
) : undefined}
{showPreview ? (
<div className={"preview-send-wrapper"}>
<div className={"preview-send-header"}>
<div className={"preview-send-header-icon"}>
</div>
<h2>
Preview
</h2>
</div>
<div className={"mt-5 preview-send-cover"}>
<img src={value of inputs} alt={"cover"}/>
</div>
<div className={" preview-send-video-poster"}>
<img src={value of inputs} alt={"cover"}/>
<h1 className={"mt-4"}>
{this.props.videoTitle} // one value of inputs get here
<span>{two value of inputs get here}</span>
</h1>
<h4 className={"mt-3"}>
{value of inputs}
</h4>
</div>
<div className={"preview-send-summary-video"}>
<p>
{value of inputs}
</p>
</div>
<Row>
<div className={"col-lg-8 col-12"}>
<button className={"send-video-btn-final"}>
Send
</button>
</div>
<div className={"col-lg-4 col-12"}>
<SendButton
onClick={() => {
setFormHidden(false);
setShowPreview(false);
setShowForm(true);
}}
/>
</div>
</Row>
</div>
) : undefined}
</div>
) : undefined}
</div>
);
};
function SendButton({onClick}) {
return (
<div>
<button className="edit-send-video-btn w-100" onClick={onClick}>
Edit
</button>
</div>
);
}
function ShowFormButton({onClick}) {
return (
<div>
<button className="upload-content-btn w-100" onClick={onClick}>
<span className="ml-2">
</span>new upload{' '}
</button>
</div>
);
}
function ShowPreviewButton({onClick}) {
return (
<div className={"row show-preview-button"}>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={onClick}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">Draft</button>
</div>
</div>
);
}
function HideFormButton({onClick}) {
return (
<div className={'content-send-form-close-btn'}>
<button onClick={onClick} className={'close-modal-btn'}>
<span>Close</span>
</button>
</div>
);
}
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
videoTitle: "",
category: "",
summary: "",
videoText: "",
}
}
onChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
return (
<div className={"content-send-form-wrapper"}>
<div className={'content-send-form-header'}>
<div className={'content-send-form-header-title'}>
</div>
</div>
<form className={'mt-3 content-send-form-data register-teacher-inputs-box '}>
<Row>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'name'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'Title'}
name={'videoTitle'}
required="true"
value={this.state.videoTitle}
onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'Title')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'country'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'category'}
name={'category'}
value={this.state.category}
onChange={this.onChange}
required="true"
onBlur={(e) => (e.target.placeholder = 'category')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload/>
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload/>
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload/>
</div>
</Row>
</form>
</div>
);
}
}

Related

Model Screen does not pop up when i submit form using React Js

I've made a react mini project about creating a nft with a form attached when the form gets approved a mini pop up occurs for approval , minting , sign and lock.
The pop up doesnt appear don't know why or where am i mistaken. can anyone help me with this , greatly appreciated!
Here's my code so far for this stuff as of this moment when i click on create console.log doesn't print
const [showmodal, setshowmodal] = useState(false);
const [showbid, setShowbid] = useState(false);
const [accounts, setaccount] = useState("");
const handleFormSubmit = async (e) => {
e.preventDefault();
console.log("form submit")
setaccount(address); //
if (validateSingle()) { // validateSingle is form verification about fields
setShowbid(true);
}
<form onSubmit={handleFormSubmit} id="form-create-item" className="form-border" encType="multipart/form-data">
<div className="field-set">
<h5>Upload file</h5>
<div className="d-create-file">
<p id="file_name">PNG, JPG, GIF, WEBP or MP4. Max 200mb.</p>
{files.map(x =>
<p key="{index}">PNG, JPG, GIF, WEBP or MP4. Max 200mb.{x.name}</p>
)}
<div className='browse'>
<input type="button" id="get_file" className="btn-main" value="Browse"/>
<input id='upload_file' type="file" className="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple onChange={handleFile} />
</div>
</div>
<div className="row" style={{paddingTop:30}}>
<div md={8} sm={8} xs={8}>
<label>Put</label>
<p className="para-color">
Receive Bid
</p>
</div>
<div md={4} sm={4} xs={4} className="text-right">
<Toggle
onClick={onToggle}
on={<h2>On</h2>}
off={<h2>Off</h2>}
size="xs"
offstyle="danger"
active={toggleActive}
/>
</div>
{toggleActive === true ? (
<div className="form-row">
<div className="form-group col-md-6">
<div className="d-flex justify-content-between align-items-start">
<span
type="button"
className={
fixed === 1
? "nft_create_btn active"
: "nft_create_btn"
}
onClick={Onfixed}
>
Fixed Price
</span>
<span
type="button"
className={
timed === 1
? "nft_create_btn active"
: "nft_create_btn"
}
onClick={Ontimed}
>
Timed Price
</span>
<span
type="button"
className={
ongoing === 1
? "nft_create_btn active"
: "nft_create_btn"
}
onClick={Auctiongoing}
>
Ongoing Auction
</span>
</div>
</div>
</div>
) : (
""
)}
</div>
<div className="row" style={{paddingTop:30}}>
<span md={8} sm={8} xs={8}>
<label>Unlock Once</label>
<p className="para-color">
Content Unlock
</p>
</span>
<span md={4} sm={4} xs={4} className="text-right">
<Toggle
onClick={onToggle2}
on={<h2>On</h2>}
off={<h2>Off</h2>}
size="xs"
offstyle="danger"
active={toggleActive2}
/>
</span>
</div>
{toggleActive2 === true && (
<div className="mb-15" style={{paddingTop:15}}>
<div md={12}>
<div className="form-group">
<input
type="text"
className="form-control primary_inp"
id="digitalkey"
name="digitalkey"
onChange={onChangeunlock}
placeholder="Digital key,code to redeem or link to a file"
/>
<span>Tip: Markdown syntax is supported</span>
</div>
</div>
</div>
)}
{toggleActive === true && fixed === 1 && (
<div className="mb-15">
<div md={12}>
<div className="form-group">
{symbol == 'ETH' ? (
<label htmlFor="price" style={{color : "white"}}>
Instant Price{" "} ({symbol})
</label>
) : (
<label htmlFor="price" style={{color : "white"}}>
Instant Price{" "} ({symbol})
</label>
)}
<input
type="text"
className="form-control input-custom"
onChange={onChangeprice}
id="price"
name="price"
value={onchangeprice}
/>
</div>
</div>
</div>
)}
{toggleActive1 === true && timed === 1 && (
<div className="form-row">
<div className="form-group col-md-12">
<label className="primary_label" htmlFor="desccription">
Date{" "}
<span className="text-muted"></span>
</label>
<div className="d-flex">
<DatePicker
className="form-control input-custom"
selected={startDate}
onChange={(date) => setStartDate(date)}
selectsStart
startDate={startDate}
endDate={endDate}
dateFormat="dd/MM/yyyy h:mm aa"
showTimeInput
/>
<DatePicker
className="form-control input-custom"
selected={endDate}
onChange={(date) => setEndDate(date)}
selectsEnd
startDate={startDate}
endDate={endDate}
minDate={startDate}
dateFormat="dd/MM/yyyy h:mm aa"
showTimeInput
/>
</div>
</div>
<div className="form-group col-md-12">
<label className="primary_label" htmlFor="name">
Minimum Bid
</label>
<div className="input_group">
<input
type="text"
className="form-control input-custom"
onChange={onChangebid}
id="minimumbid"
name="minimumbid"
placeholder="Minimum Bid"
/>
</div>
</div>
</div>
)}
<div className="spacer-single"></div>
<h5>Title</h5>
<input type="text" name="item_title" id="name" className="form-control" placeholder="e.g. 'Crypto Funk" onChange={onChange}/>
<div className="spacer-10"></div>
<h5>Description</h5>
<textarea data-autoresize name="item_desc" id="description" className="form-control" placeholder="e.g. 'This is very limited item'" onChange={onChangeDescription}></textarea>
<div className="spacer-10"></div>
<div className="mb-15">
<div md={12}>
<div className="form-group">
<label htmlFor="category" style={{color:"white"}}>
Category
</label>
<Select
className=""
id="tokenCategory"
onChange={HandleChange}
options={CategoryOption}
/>
</div>
</div>
</div>
{/* <h5>Price in {symbol}</h5>
<input type="text" name="item_price" id="item_price" className="form-control" /> */}
<div className="spacer-10"></div>
<h5>Royalties</h5>
<input type="text" name="item_royalties" id="royalties" className="form-control" placeholder="suggested: 0, 10%, 20%, 30%. Maximum is 70%" onChange={onChangeroy}/>
<div className="spacer-10"></div>
<input type="button" id="submit" value="Create Item" className="connect-wallet create-item btn-main"/>
</div>
</form>
//Modal pop up
<Modal
show={showbid}
size="md"
backdrop="static"
onHide={handleClosebid}
centered
id="follow-steps-modal"
className="custom-style-modal"
>
<Modal.Header closeButton>
<Modal.Title>{language[localStorageLang].FOLLOW_STEPS}</Modal.Title>
</Modal.Header>
<Modal.Body className="pl-30 pr-30">
<Row>
<Col sm={2} md={2} className="col-xs-2">
{approveprograss === false ? (
<div className="follow-step-1-icon">
<i className="fa fa-check-circle"></i>
</div>
) : (
<div className="follow-step-2-icon">
<div className="loader"></div>
</div>
)}
</Col>
<Col sm={6} md={6} className="col-xs-10">
<div className="follow-step-1-content">
<h4>{language[localStorageLang].APPROVE}</h4>
<p className="para-color">
{language[localStorageLang].CHECKING_BALANCE}
</p>
</div>
</Col>
<Col sm={4} md={4} className="col-xs-12">
{approveprograss === false ? (
<div>
{approvesuccess === false ? (
<div className="follow-step-1-button">
<Link to="#" onClick={approve} disabled>
{language[localStorageLang].TRY_AGAIN}
</Link>
</div>
) : (
<div>
{approvesuccess === true ? (
<div className="follow-step-1-button">
<Link to="#" disabled>
{language[localStorageLang].DONE}
</Link>
</div>
) : (
<div className="follow-step-1-button">
<Link to="#" onClick={approve} className="">
{language[localStorageLang].START}
</Link>
</div>
)}
</div>
)}
</div>
) : (
<div className="follow-step-2-button">
<Link to="#" className="">
{language[localStorageLang].INPROGRESS}
</Link>
</div>
)}
</Col>
</Row>
<Row>
<Col sm={12} md={12}>
<hr />
</Col>
</Row>
<Row>
<Col sm={2} md={2} className="col-xs-2">
{uploadprograss === false ? (
<div className="follow-step-1-icon">
<i className="fa fa-check-circle"></i>
</div>
) : (
<div className="follow-step-2-icon">
<div className="loader"></div>
</div>
)}
</Col>
<Col sm={6} md={6} className="col-xs-10">
<div className="follow-step-2-content">
<h4>{language[localStorageLang].UPLOAD}</h4>
<p className="para-color">
{language[localStorageLang].CHECKING_BALANCE}
</p>
</div>
</Col>
<Col sm={4} md={4} className="col-xs-12">
{uploadprograss === false ? (
<div>
{uploadsuccess === false ? (
<div className="follow-step-1-button">
<Link to="#" onClick={mintCalling} disabled>
{language[localStorageLang].TRY_AGAIN}
</Link>
</div>
) : (
<div>
{uploadsuccess === true ? (
<div className="follow-step-1-button">
<Link to="#" disabled>
{language[localStorageLang].DONE}
</Link>
</div>
) : (
<div className="follow-step-1-button">
<Link to="#" onClick={mintCalling}>
{language[localStorageLang].START}
</Link>
</div>
)}
</div>
)}
</div>
) : (
<div className="follow-step-2-button">
<Link to="#" className="">
{language[localStorageLang].INPROGRESS}
</Link>
</div>
)}
</Col>
</Row>
<Row>
<Col sm={12} md={12}>
<hr />
</Col>
</Row>
<Row>
<Col sm={2} md={2} className="col-xs-2">
{sellprograss === false ? (
<div className="follow-step-1-icon">
<i className="fa fa-check-circle"></i>
</div>
) : (
<div className="follow-step-2-icon">
<div className="loader"></div>
</div>
)}
</Col>
<Col sm={6} md={6} className="col-xs-10">
<div className="follow-step-3-content">
<h4>Sign sell order</h4>
<p className="para-color">
{language[localStorageLang].CREATE_SIGNATURE}
</p>
</div>
</Col>
<Col sm={4} md={4} className="col-xs-12">
{sellprograss === false ? (
<div>
{sellsuccess === false ? (
<div className="follow-step-1-button">
<Link to="#" onClick={signsell} disabled>
{language[localStorageLang].TRY_AGAIN}
</Link>
</div>
) : (
<div>
{sellsuccess === true ? (
<div className="follow-step-1-button">
<Link to="#" disabled>
Done
</Link>
</div>
) : (
<div className="follow-step-1-button">
<Link to="#" onClick={signsell}>
{language[localStorageLang].START}
</Link>
</div>
)}
</div>
)}
</div>
) : (
<div className="follow-step-2-button">
<Link to="#" className="">
{language[localStorageLang].INPROGRESS}
</Link>
</div>
)}
</Col>
</Row>
<Row>
<Col sm={12} md={12}>
<hr />
</Col>
</Row>
<Row>
<Col sm={2} md={2} className="col-xs-2">
{lockprograss === false ? (
<div className="follow-step-1-icon">
<i className="fa fa-check-circle"></i>
</div>
) : (
<div className="follow-step-2-icon">
<div className="loader"></div>
</div>
)}
</Col>
<Col sm={6} md={6} className="col-xs-10">
<div className="follow-step-3-content">
<h4>{language[localStorageLang].SIGN_LOCK_ORDER}</h4>
<p className="para-color">
{language[localStorageLang].SIGN_LOCK_WALLET}
</p>
</div>
</Col>
<Col sm={4} md={4} className="col-xs-12">
{lockprograss === false ? (
<div>
{locksuccess === false ? (
<div className="follow-step-1-button">
<Link to="#" onClick={signlock} disabled>
{language[localStorageLang].TRY_AGAIN}
</Link>
</div>
) : (
<div>
{locksuccess === true ? (
<div className="follow-step-1-button">
<Link to="#" disabled>
{language[localStorageLang].DONE}
</Link>
</div>
) : (
<div className="follow-step-1-button">
<Link to="#" onClick={signlock}>
{language[localStorageLang].START}
</Link>
</div>
)}
</div>
)}
</div>
) : (
<div className="follow-step-2-button">
<Link to="#" className="">
{language[localStorageLang].INPROGRESS}
</Link>
</div>
)}
</Col>
</Row>
</Modal.Body>
</Modal>
Let me know if anything else is required , was trying to resolve this since long time but unable to !

Doing real-time calculations in a form in react js components

I'm a new user to React and I'm having trouble with my app.. Basically I want to do some calculation when the user input some values it dynamically outputs the amount. The calculation should add the packaging amt with transport amt and subtract the discount amt, the result is then added to the product of kgs with price per kg to show the total amt. . If anyone can help me with this it would be very much appreciated. My code is included below `
import React from "react";
import APIHandler from "../utils/APIHandler";
import { Link } from "react-router-dom";
import AutoCompleteCustomer from "../components/AutoCompleteCustomer";
class HomeComponent extends React.Component {
constructor(props) {
super(props);
this.formSubmit = this.formSubmit.bind(this);
}
state = {
errorRes: false,
errorMessage: "",
btnMessage: 0,
sendData: false,
farmerlist: [],
customersDetails: [{
phone: "",
name: "",
}],
dataLoaded: false,
value: ""
};
async formSubmit(event) {
event.preventDefault();
this.setState({ btnMessage: 1 });
var apiHandler = new APIHandler();
var response = await apiHandler.saveOrdersData(
event.target.phone.value,
event.target.id.value,
event.target.town.value,
event.target.region.value,
event.target.kgs.value,
event.target.packaging.value,
event.target.discount.value,
event.target.transport.value,
event.target.comment.value,
event.target.farmer_id.value,
event.target.price.value,
event.target.amount.value,
);
console.log(response);
this.setState({ btnMessage: 0 });
this.setState({ errorRes: response.data.error });
this.setState({ errorMessage: response.data.message });
this.setState({ sendData: true });
}
//This Method Work When Our Page is Ready
componentDidMount() {
this.LoadFarmer();
}
async LoadFarmer() {
var apihandler = new APIHandler();
var farmerdata = await apihandler.fetchFarmerOnly();
this.setState({ farmerlist: farmerdata.data });
}
showDataInInputs = (index, item) => {
console.log(index);
console.log(item);
this.setState.customersDetails[index].phone = item.phone;
this.setState.customersDetails[index].id = item.id;
}
viewRequestDetails = (request_id) => {
console.log(request_id);
console.log(this.props);
this.props.history.push("/ordersDetails/" + request_id);
};
qtyChangeUpdate = (event) => {
var value = event.target.value;
this.state.total =
((parseInt(this.state.packaging) +
parseInt(this.state.transport) -
parseInt(this.state.discount)) +
(parseInt(this.state.kgs) * parseInt(this.state.price))) * value;
this.state.amount = value;
this.setState({});
};
render() {
return (
<section className="content">
<div className="container-fluid">
<div className="block-header">
<h2>MANAGE ORDERS & CUSTOMERS</h2>
</div>
<div className="row clearfix">
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="card">
<div className="header">
<h2>Add Order</h2>
<ul className="header-dropdown m-r--5">
<Link to="/addcustomer" className="toggled waves-effect waves-block">
<button className="btn btn-primary m-r-15 waves-effect">
Add Customer
</button>
</Link>
</ul>
</div>
<div className="body">
<form onSubmit={this.formSubmit}>
{this.state.customersDetails.map((item, index) => (
<div className="row" key={index}>
<div className="col-lg-6">
<label htmlFor="email_address">
Phone No.{" "}
</label>
<div className="form-group">
<div className="form-line">
<AutoCompleteCustomer
itemPostion={index}
showDataInInputs={this.showDataInInputs}
/>
</div>
</div>
</div>
<div className="col-lg-6">
<label htmlFor="email_address">Customer Name</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="id"
name="id"
className="form-control"
placeholder="Enter Customer Name"
defaultValue={item.id}
data-index={index}
/>
</div>
</div>
</div>
</div>
))}
<div className="row">
<div className="col-lg-4">
<label htmlFor="email_address">Town</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="town"
name="town"
className="form-control"
placeholder="Enter Customer Town"
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Region</label>
<div className="form-group">
<div className="form-line">
<select id="region" name="region" className="form-control show-tick">
<option value="1">Nairobi</option>
<option value="2">Nyanza</option>
<option value="3">Central</option>
<option value="4">Coast</option>
<option value="5">Eastern</option>
<option value="6">North Eastern</option>
<option value="7">Western</option>
<option value="8">Rift Valley</option>
</select>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Kgs : </label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="kgs"
name="kgs"
className="form-control"
placeholder="Enter Quantity."
defaultValue={this.state.kgs}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Packaging</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="packaging"
name="packaging"
className="form-control"
placeholder="Enter Amount"
defaultValue={this.state.packaging}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Discount.</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="discount"
name="discount"
className="form-control"
placeholder="Enter Discount."
defaultValue={this.state.discount}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Transport</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="transport"
name="transport"
className="form-control"
placeholder="Enter Transport."
defaultValue={this.state.transport}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Comment</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="comment"
name="comment"
className="form-control"
placeholder="Enter Comment"
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Farmer Name</label>
<div className="form-group">
<select className="form-control show-tick"
id="farmer_id"
name="farmer_id"
>
{this.state.farmerlist.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Price per Kg</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="price"
name="price"
className="form-control"
placeholder="Enter Price"
defaultValue={this.state.price}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Amount</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="amount"
name="amount"
className="form-control"
placeholder="Enter Amount"
value={this.state.amount}
onChange={this.qtyChangeUpdate}
/>
</div>
</div>
</div>
</div>
<br />
<button
type="submit"
className="btn btn-success m-t-15 waves-effect "
disabled={this.state.btnMessage === 0 ? false : true}
>
{this.state.btnMessage === 0
? "Add Order"
: "Adding Order Please Wait.."}
</button>
<br />
{this.state.errorRes === false &&
this.state.sendData === true ? (
<div className="alert alert-success">
<strong>Success!</strong> {this.state.errorMessage}.
</div>
) : (
""
)}
{this.state.errorRes === true &&
this.state.sendData === true ? (
<div className="alert alert-danger">
<strong>Failed!</strong>
{this.state.errorMessage}.
</div>
) : (
""
)}
</form>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default HomeComponent;
I managed to get this working by using setState an binding event to the form
import React from "react";
import APIHandler from "../utils/APIHandler";
import { Link } from "react-router-dom";
import AutoCompleteCustomer from "../components/AutoCompleteCustomer";
class HomeComponent extends React.Component {
constructor(props) {
super(props);
this.formSubmit = this.formSubmit.bind(this);
this.updateKgs = this.updateKgs.bind(this);
this.updatePackaging = this.updatePackaging.bind(this);
this.updateDiscount = this.updateDiscount.bind(this);
this.updateTransport = this.updateTransport.bind(this);
this.updatePrice = this.updatePrice.bind(this);
this.formRef = React.createRef();
}
state = {
errorRes: false,
errorMessage: "",
btnMessage: 0,
sendData: false,
farmerlist: [],
kgs: "",
price: "",
packaging: "",
discount: "",
transport: "",
amount: "",
customersDetails: [
{
id: 0,
phone: "",
name: "",
customer_id: "",
},
],
dataLoaded: false,
};
async formSubmit(event) {
event.preventDefault();
this.setState({ btnMessage: 1 });
var apiHandler = new APIHandler();
var response = await apiHandler.saveOrdersData(
event.target.phone.value,
event.target.name.value,
event.target.customer_id.value,
event.target.town.value,
event.target.region.value,
event.target.kgs.value,
event.target.packaging.value,
event.target.discount.value,
event.target.transport.value,
event.target.comment.value,
event.target.farmer_id.value,
event.target.rice_type.value,
event.target.price.value,
event.target.amount.value,
);
console.log(response);
this.setState({ btnMessage: 0 });
this.setState({ errorRes: response.data.error });
this.setState({ errorMessage: response.data.message });
this.setState({ sendData: true });
this.formRef.current.reset();
}
//This Method Work When Our Page is Ready
componentDidMount() {
this.LoadFarmer();
}
async LoadFarmer() {
var apihandler = new APIHandler();
var farmerdata = await apihandler.fetchFarmerOnly();
this.setState({ farmerlist: farmerdata.data });
}
showDataInInputs = (index, item) => {
console.log(index);
console.log(item);
this.state.customersDetails[index].id = item.id;
this.state.customersDetails[index].phone = item.phone;
this.state.customersDetails[index].name = item.name;
this.state.customersDetails[index].customer_id = item.id;
this.setState({})
}
updateKgs = (event) => {
this.setState({
kgs: event.target.value
});
}
updatePackaging = (event) => {
this.setState({
packaging: event.target.value
});
console.log(this.state.packaging)
}
updateDiscount = (event) => {
this.setState({
discount: event.target.value
});
}
updateTransport = (event) => {
this.setState({
transport: event.target.value
});
}
updatePrice = (event) => {
this.setState({
price: event.target.value
});
}
updateAmount = () => {
this.setState({
amount: (Number(this.state.kgs) * Number(this.state.price)) + Number(this.state.packaging) + Number(this.state.transport) - Number(this.state.discount)
});
}
render() {
return (
<section className="content">
<div className="container-fluid">
<div className="block-header">
<h2>ADD ORDERS & CUSTOMERS</h2>
</div>
<div className="row clearfix">
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div className="card">
<div className="header">
<h2>Add Order</h2>
<ul className="header-dropdown m-r--5">
<Link to={"/addcustomer"} className="toggled waves-effect waves-block">
<button className="btn btn-primary m-r-15 waves-effect">
Add Customer
</button>
</Link>
</ul>
</div>
<div className="body">
<form onSubmit={this.formSubmit} ref={this.formRef}>
{this.state.customersDetails.map((item, index) => (
<div className="row" key={index}>
<div className="col-lg-6">
<label htmlFor="email_address">
Phone No.{" "}
</label>
<div className="form-group">
<div className="form-line">
<AutoCompleteCustomer
itemPostion={index}
showDataInInputs={this.showDataInInputs}
/>
</div>
</div>
</div>
<div className="col-lg-5">
<label htmlFor="email_address">Customer Name</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="name"
name="name"
className="form-control"
placeholder="Enter Customer Name"
defaultValue={item.name}
/>
</div>
</div>
</div>
<div className="col-sm-1">
<label htmlFor="email_address">No</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="customer_id"
name="customer_id"
className="form-control"
placeholder=""
value={item.customer_id}
/>
</div>
</div>
</div>
</div>
))}
<div className="row">
<div className="col-lg-4">
<label htmlFor="email_address">Town</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="town"
name="town"
className="form-control"
placeholder="Enter Customer Town"
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Region</label>
<div className="form-group">
<div className="form-line">
<select id="region" name="region" className="form-control show-tick">
<option value="1">NAIROBI</option>
<option value="2">NYANZA</option>
<option value="3">CENTRAL</option>
<option value="4">COAST</option>
<option value="5">EASTERN</option>
<option value="6">NORTH EASTERN</option>
<option value="7">WESTERN</option>
<option value="8">RIFT VALLEY</option>
</select>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Kgs : </label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="kgs"
name="kgs"
className="form-control"
placeholder="Enter Quantity."
defaultValue={this.state.kgs}
onChange={this.updateKgs}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Packaging</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="packaging"
name="packaging"
className="form-control"
placeholder="Enter Amount"
defaultValue={this.state.packaging}
onChange={this.updatePackaging}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Discount.</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="discount"
name="discount"
className="form-control"
placeholder="Enter Discount."
defaultValue={this.state.discount}
onChange={this.updateDiscount}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Transport</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="transport"
name="transport"
className="form-control"
placeholder="Enter Transport."
defaultValue={this.state.transport}
onChange={this.updateTransport}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Comment</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="comment"
name="comment"
className="form-control"
placeholder="Enter Comment"
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Farmer Name</label>
<div className="form-group">
<select className="form-control show-tick"
id="farmer_id"
name="farmer_id"
>
{this.state.farmerlist.map((item) => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Rice Type</label>
<div className="form-group">
<div className="form-line">
<select id="rice_type" name="rice_type" className="form-control show-tick">
<option value="1">Pishori</option>
<option value="2">Komboka</option>
</select>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Price per Kg</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="price"
name="price"
className="form-control"
placeholder="Enter Price"
defaultValue={this.state.price}
onChange={this.updatePrice}
/>
</div>
</div>
</div>
<div className="col-lg-4">
<label htmlFor="email_address">Amount</label>
<div className="form-group">
<div className="form-line">
<input
type="text"
id="amount"
name="amount"
className="form-control"
placeholder="Enter Amount"
defaultValue={this.state.amount}
onClick={this.updateAmount}
/>
</div>
</div>
</div>
</div>
<br />
<button
type="submit"
className="btn btn-success m-t-15 waves-effect "
disabled={this.state.btnMessage === 0 ? false : true}
>
{this.state.btnMessage === 0
? "Add Order"
: "Adding Order Please Wait.."}
</button>
<br />
{this.state.errorRes === false &&
this.state.sendData === true ? (
<div className="alert alert-success">
<strong>Success!</strong> {this.state.errorMessage}.
<Link to="/orders" className="btn btn-info">View Orders</Link>
</div>
) : (
""
)}
{this.state.errorRes === true &&
this.state.sendData === true ? (
<div className="alert alert-danger">
<strong>Failed!</strong>
{this.state.errorMessage}.
</div>
) : (
""
)}
</form>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
}
export default HomeComponent;
Hope this helpful to anyone facing a similar problem..

React needs to be handled some if conditions

I have an issue with the if statement. The problem is I need to create a condition if the array has 2 object needs to be true if has 1 object it should be false. the objects are strings please check the code.
const { program } = useContext(ProgramContext);
const { authMethods } = program;
let loginComponent;
let claimComponent;
let insertRow;
let insertEnd;
if (authMethods) {
if (authMethods.indexOf('login') !== -1) {
loginComponent = (
<div className="col-md-6 d-flex">
<div className="card flex-grow-1 mb-md-0">
<div className="card-body">
<h3 className="card-title">Login</h3>
<form>
<div className="form-group">
<label htmlFor="login-id">User ID</label>
<input
id="login-id"
className="form-control"
placeholder="Please enter user ID"
/>
</div>
<div className="form-group">
<label htmlFor="login-password">Password</label>
<input
id="login-password"
type="password"
className="form-control"
placeholder="Password"
/>
<small className="form-text text-muted">
<ErrModal />
</small>
</div>
<div className="form-group">
<div className="form-check">
<span className="form-check-input input-check">
<span className="input-check__body">
<input
id="login-remember"
type="checkbox"
className="input-check__input"
/>
<span className="input-check__box" />
<Check9x7Svg className="input-check__icon" />
</span>
</span>
<label className="form-check-label" htmlFor="login-remember">
Remember Me
</label>
</div>
</div>
<button type="submit" className="btn btn-primary mt-2 mt-md-3 mt-lg-4">
Login
</button>
</form>
</div>
</div>
</div>
);
}
if (authMethods.indexOf('claim') !== -1) {
claimComponent = (
<div className="col-md-6 d-flex mt-4 mt-md-0">
<div className="card flex-grow-1 mb-0">
<div className="card-body">
<h3 className="card-title">Claim</h3>
<form>
<div className="form-group">
<label htmlFor="claim-code">Enter Claim Code</label>
<input
id="register-email"
type="text"
className="form-control"
placeholder="Claim Code"
/>
</div>
<button type="submit" className="btn btn-primary" style={{ marginTop: '186px' }}>
Claim
</button>
</form>
</div>
</div>
</div>
);
}
}
console.log(loginComponent);
console.log(claimComponent);
const rowComponent = (
<div className="container">
{insertRow}
{loginComponent}
{claimComponent}
{insertEnd}
</div>
);
Basically I want to add row class if there are 2 items in the array otherwise I don't need a row.
thank you
Your question is not clear so I'll chalk out a similar example:
import React from 'react'
const Component = () => {
const arr = ["foo", "bar"];
const rowClass = arr.length === 2 ? "row" : "";
return (
<div className={rowClass}>
This is an example
</div>
)
}
export default Component

Closing a modal on clicking outside it with React Hooks

I'm trying to create a pop up subscription box which closes whenever one clicks on the close button or clicks anywhere outside the pop up. I've created a modal component and a state showModal which is used to toggle the visibility of this Modal. I have tried to add setShowModal(false) to the outer div element but that just disables the whole modal. What can be done to close the modal whenever we click outside the modal. This is how my main page looks
const [showModal, setShowModal] = useState(false);
return (
<>
<div
className="homepage"
style={{
filter: showModal ? "blur(8px)" : "none",
minHeight:"80vh",
}}
>
<section
className="homepage-hero"
style={{ paddingBottom:"-2rem", minHeight:"100vh" }}
>
<div className="hero-body">
<div className="container">
<div className="columns">
<div className="column ">
<h1>
<span className="heading">
Finance <br />
Scheme
</span>
<br />
</h1>
<p>
Lorem Ipsum
</p>
<div className="is-hidden-tablet">
</div>
<div className="button-group">
<button
style={{
fontWeight: "600",
padding: "0.75em 1.9em",
borderRadius: "0px",
color: "white",
backgroundColor: "#24ca7a",
border: "1px solid #24ca7a",
cursor: "pointer",
}}
onClick={() => setShowModal(true)}
>
Download
</button>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{showModal && (
<Modal
modalId="signup-modal"
onClose={() => setShowModal(false)}
canDismiss={false}
modalWidth="70%"
style={{position:"fixed", top:"20", minHeight:"50vh"}}
>
<div className="contact-us" style={{ margin:"20px"}}>
<section className="contact-form" >
<div className="container">
<div className="columns is-8 ">
<div
className="column is-half-desktop is-full-mobile container-content"
style={{ boxShadow: "none" }}
>
{submitted ? (
<div className="success">
<img src={confirmedIllus} alt="" />
<h2>Your details have been submitted successfully!</h2>
</div>
) : (
<form onSubmit={handleOnSubmit} id="contact-form" >
<h1 className="heading" style={{ fontSize: "2rem" }}>
Your Details
</h1>
<br />
<div className="field">
<label className="label">Name</label>
<div className="control">
<input
className="input"
id="name"
value={name}
type="text"
placeholder="Your Full Name"
onChange={(e) => setName(e.target.value)}
required
/>
</div>
</div>
<div className="field">
<label className="label">Email</label>
<div className="control ">
<input
className={`input ${isDanger}`}
id="email"
value={email}
type="email"
onChange={handleOnChange}
placeholder="Your Email"
required
/>
{!validEmail && isDanger ? (
<span className="icon is-small is-right">
<i className="material-icons-round">warning</i>
</span>
) : (
" "
)}
</div>
{!validEmail && isDanger ? (
<p className="help is-danger">{emailMessage}</p>
) : (
""
)}
</div>
<div className="field is-grouped submit-button-group">
<div className="control">
<button
style={{
cursor: !validEmail ? "not-allowed" : "pointer",
}}
className="button submit-button"
id="submit-form"
>
Submit
</button>
</div>
</div>
</form>
)}
</div>
<div className="column is-half-desktop is-full-mobile " >
<img
src="/images/Ebook.svg"
className="is-hidden-mobile"
style={{ width: "70%", marginTop: "40%" }}
/>
<div className=" font-blue bottom-text">
Fill your details to download the free <b> Ebook </b>
</div>
</div>
</div>
</div>
</section>
</div>
</Modal>
)}
</>
);
You can use the useOnClickOutside hook. This hook allows you to detect clicks outside of a specified element.
You have to import the followings
Create a ref that we add to the element for which we want to detect outside clicks
const ref = useRef();
State for our modal
const [showModal, setShowModal] = useState(false);
Call hook passing in the ref and a function to call on outside click
useOnClickOutside(ref, () => setShowModal(false));
render here
return(...);
//Hook
import { useEffect } from 'react';
export default function useOnClickOutside(ref, handler) {
useEffect(
() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
},
// Add ref and handler to effect dependencies
// It's worth noting that because the passed-in handler is a new ...
// ... function on every render that will cause this effect ...
// ... callback/cleanup to run every render. It's not a big deal ...
// ... but to optimize you can wrap handler in useCallback before ...
// ... passing it into this hook.
[ref, handler]
);
}
See related repl output here - https://spanishhotloaderprogram.thelovekesh.repl.co/
For this, you can give tabIndex=-1 to your modal div, and then you can use the onBlur event.
const [showModal, setShowModal] = useState(false);
return (
<>
<div
className="homepage"
style={{
filter: showModal ? "blur(8px)" : "none",
minHeight:"80vh",
}}
>
<section
className="homepage-hero"
style={{ paddingBottom:"-2rem", minHeight:"100vh" }}
>
<div className="hero-body">
<div className="container">
<div className="columns">
<div className="column ">
<h1>
<span className="heading">
Finance <br />
Scheme
</span>
<br />
</h1>
<p>
Lorem Ipsum
</p>
<div className="is-hidden-tablet">
</div>
<div className="button-group">
<button
style={{
fontWeight: "600",
padding: "0.75em 1.9em",
borderRadius: "0px",
color: "white",
backgroundColor: "#24ca7a",
border: "1px solid #24ca7a",
cursor: "pointer",
}}
onClick={() => setShowModal(true)}
>
Download
</button>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{showModal && (
<Modal
modalId="signup-modal"
onBlur={() => setShowModal(false)}
canDismiss={false}
modalWidth="70%"
style={{position:"fixed", top:"20", minHeight:"50vh"}}
tabIndex={-1}
>
<div className="contact-us" style={{ margin:"20px"}}>
<section className="contact-form" >
<div className="container">
<div className="columns is-8 ">
<div
className="column is-half-desktop is-full-mobile container-content"
style={{ boxShadow: "none" }}
>
{submitted ? (
<div className="success">
<img src={confirmedIllus} alt="" />
<h2>Your details have been submitted successfully!</h2>
</div>
) : (
<form onSubmit={handleOnSubmit} id="contact-form" >
<h1 className="heading" style={{ fontSize: "2rem" }}>
Your Details
</h1>
<br />
<div className="field">
<label className="label">Name</label>
<div className="control">
<input
className="input"
id="name"
value={name}
type="text"
placeholder="Your Full Name"
onChange={(e) => setName(e.target.value)}
required
/>
</div>
</div>
<div className="field">
<label className="label">Email</label>
<div className="control ">
<input
className={`input ${isDanger}`}
id="email"
value={email}
type="email"
onChange={handleOnChange}
placeholder="Your Email"
required
/>
{!validEmail && isDanger ? (
<span className="icon is-small is-right">
<i className="material-icons-round">warning</i>
</span>
) : (
" "
)}
</div>
{!validEmail && isDanger ? (
<p className="help is-danger">{emailMessage}</p>
) : (
""
)}
</div>
<div className="field is-grouped submit-button-group">
<div className="control">
<button
style={{
cursor: !validEmail ? "not-allowed" : "pointer",
}}
className="button submit-button"
id="submit-form"
>
Submit
</button>
</div>
</div>
</form>
)}
</div>
<div className="column is-half-desktop is-full-mobile " >
<img
src="/images/Ebook.svg"
className="is-hidden-mobile"
style={{ width: "70%", marginTop: "40%" }}
/>
<div className=" font-blue bottom-text">
Fill your details to download the free <b> Ebook </b>
</div>
</div>
</div>
</div>
</section>
</div>
</Modal>
)}
</>
);
In your div className homepage you can use a condition when you click, if showModal is true --> setShowModal to false like
<div
className="homepage"
style={{
filter: showModal ? "blur(8px)" : "none",
minHeight: "80vh",
}}
onClick={() => showModal && setShowModal(false)}
>

Custom React component(react-hook) not re-rendering

I have a component that fetches data from my mongoDB it then renders a list of child components. It the "list" component I have a post that adds a new member to the database. Upon addition im trying to get the list to re-fetch the data and re-render the list component.
List Component:
import React, { useState, useEffect } from "react";
import axios from "axios";
import Spinner from "react-bootstrap/Spinner";
import { toast } from "react-toastify";
import DatePicker from "react-datepicker";
import useForm from "react-hook-form";
import { css } from "glamor";
import "react-toastify/dist/ReactToastify.css";
import "react-datepicker/dist/react-datepicker.css";
import "../Styles/ReactDatePicker.css";
import Member from "./Member";
const { getFamily, getMembers, postMember } = require("../Utils/Service");
const MemberList = () => {
const [family, setFamily] = useState({});
const [familyMembers, setFamilyMembers] = useState([]);
const [loading, setLoading] = useState(true);
const [date, setDate] = useState(new Date());
const { handleSubmit, register, errors } = useForm();
async function fetchData() {
getFamily.then(result => {
setFamily(result);
});
getMembers.then(result => {
try {
setFamilyMembers(
result.map((child, index) => (
<Member
key={index}
index={child._id}
balance={child.balance}
firstName={child.firstName}
lastName={child.lastName}
birthday={child.birthday}
role={child.role[0]}
/>
))
);
} catch (e) {
toast.error("500: Error with Service Call", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
className: css({
background: "#ed5565 !important"
})
});
} finally {
setLoading(false);
}
});
}
useEffect(() => {
if (loading) {
fetchData();
}
}, [loading]);
// const handleDateChange = date => {
// setDate(date)
// }
const onSubmit = data => {
data.familyId = "5dddf14df965552b3da57be1";
postMember(data).then(
????????????
);
};
return (
<div className="ibox">
<div className="ibox-title">
<h5>{family.name}</h5>
<div className="ibox-tools">
<span className="label label-warning-light float-right">
{familyMembers.length} Member(s)
</span>
</div>
</div>
<div className="ibox-content">
<div className="feed-activity-list">
{loading ? (
<Spinner animation="grow" role="status" variant="dark">
<span className="sr-only">Loading...</span>
</Spinner>
) : (
familyMembers
)}
</div>
<div className="d-flex">
<a
className="btn btn-primary text-white m-t"
data-toggle="modal"
data-target={"#newMemberModel"}
>
<i className="fa fa-plus"></i> New Member
</a>
<a
className="btn btn-danger text-white m-t m-l"
data-toggle="modal"
data-target={"#removeMemberModel"}
>
<i className="fa fa-minus"></i> Remove Member
</a>
</div>
</div>
{/* New Member Model */}
<div
className="modal inmodal"
id={"newMemberModel"}
tabIndex="-1"
role="dialog"
style={{ display: "none" }}
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content animated fadeIn">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">New Family Member</h4>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="modal-body">
<div className="row">
<div className="col">
<div className="form-group">
<label>First Name</label>
<input
type="text"
placeholder="First Name"
className="form-control"
name="firstName"
ref={register({
required: true,
pattern: {
value: /^[a-zA-Z]+$/i,
message: "Invalid First Name"
}
})}
/>
<div className="text-danger">
{errors.firstName && errors.firstName.message}
</div>
</div>
<div className="form-group">
<label className="font-normal">Birthday</label>
<div className="input-group date">
{/* <DatePicker
selected={date}
onChange={handleDateChange}
placeholderText="Click to select a date"
isClearable
peekNextMonth
showMonthDropdown
showYearDropdown
dropdownMode="select"
ref={e =>register({
name: "Birthday",
required: false
})}
/> */}
<input
type="text"
placeholder="01/01/01"
className="form-control"
name="birthDate"
ref={register({
required: false
})}
/>
</div>
</div>
</div>
<div className="col">
<div className="form-group">
<label>Last Name</label>
<input
type="text"
placeholder="Last Name"
className="form-control"
name="lastName"
ref={register({
required: true,
pattern: {
value: /^[a-zA-Z]+$/i,
message: "Invalid Last Name"
}
})}
/>
<div className="text-danger">
{errors.lastName && errors.lastName.message}
</div>
</div>
<div className="form-group">
<label>Role</label>
<select
className="custom-select"
name="role"
ref={register({ required: true })}
>
<option defaultValue>Select Role</option>
<option value="Adult">Adult</option>
<option value="Child">Child</option>
</select>
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-white"
data-dismiss="modal"
>
Close
</button>
<button type="submit" className="btn btn-primary">
Add Member
</button>
</div>
</form>
</div>
</div>
</div>
{/* Remove Member Model */}
<div
className="modal inmodal"
id={"removeMemberModel"}
tabIndex="-1"
role="dialog"
style={{ display: "none" }}
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content animated fadeIn">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h4 className="modal-title">Remove Family Member</h4>
</div>
<div className="modal-body"></div>
<div className="modal-footer">
<button
type="button"
className="btn btn-white"
data-dismiss="modal"
>
Close
</button>
<button type="button" className="btn btn-danger">
Remove Member
</button>
</div>
</div>
</div>
</div>
</div>
);
};
export default MemberList;
within the code in the onSubmit function with posts the data inside the .then is where im trying to re-render the entire component and/or fetch the data agin.
right now, your useEffect is only dependent on the property loading, if you change the property then the effect will run again.
https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect
In your component, you can call this.forceUpdate() to force a rerender.
I think you can also call your fetchData function again inside your .then() block, if you make the callback inside the .then() an async function.
postMember(data).then(
async () => this.fetchData()
);
or
postMember(data).then(
() => this.forceUpdate()
);

Categories

Resources