I am trying to familiarize myself with sending POST data, this time using React. In this instance, I am attempting to do it without a form.
My front-end React code specifically looks like so:
stockconfirmbuy: function(){
var stin = this.refs.stockpriceref.innerHTML;
var totalbuyval = stin * this.state.stockdnum;
return (<div>
<p>Are you sure you would like to buy {this.refs.stocknameref.innerHTML} stock at ${this.refs.stockpriceref.innerHTML} per share?</p>
<p>Select Amount:</p>
<input className="form-control" defaultValue="1" type="number" value={this.state.stockdum} onChange={this.changestocknum} />
<p>Your Total:</p>
<p>${totalbuyval}</p>
<div id="buttongroups">
<button className="btn btn-success" onClick={this.buyprocess}>Buy It</button>
<button className="btn btn-danger" onClick={this.cancelprocess}>Cancel</button>
</div>
</div>);
},
My initial stockdnum
state value is 1, for clarity's sake.
Meanwhile, my schema is arranged like so:
var UserSchema = new Schema({
email: { type: String, unique: true, lowercase: true},
password: String,
icapital: {type: Number, default: 9001},
profile: {
name: { type: String, default: ''},
picture: { type: String, default: ''}
},
address: String,
history: [{
date: Date,
stocklabel: String,
stockname: String,
stocknumber: Number,
stockpaid: Number
}]
});
My attempt at coding the transaction into my routes/user.js
page looks like so:
router.post('/profile', function(req, res, next) {
User.findOne({ _id: req.user._id }, function(err, user) {
if (err) return next(err);
if (req.body.stocklabel) user.history.stocklabel = req.body.stocklabel;
if (req.body.stockname) user.history.stockname = req.body.stockname;
user.history.date = Date();
if (req.body.stocknumber) user.history.stocknumber = req.body.stocknumber;
if (req.body.stockprice) user.history.stockprice = req.body.stockprice;
user.save(function(err) {
if (err) return next(err);
req.flash('success', 'Purchase sucessful');
return res.redirect('/profile');
});
});
});
First, I would like to make sure that my transaction lines up with the arrangement of my Schema.
Second, going back to my front-end React code, I am not sure how to take the relevant data from my React into my DB. I want the operation to run on {this.buyprocess}
. However, since it is not a traditional input form, I am unsure how to turn it into a submit button that transfers these following pieces of info.
{this.refs.stockpriceref.innerHTML}
repressents the stock label.
{this.state.stockdnum}
represents the amount, or the stock number.
{totalbuyval}
represents the total cost, or the stock price.
I am not sure what the code in the this.buyprocess
function would look like.