Need to check if the value being submitted is greater than the current value

Viewed 128

Needing to check that a users bid is greater than the current bid/price. Currently I'm getting back that the input is always less than the current bid/ price. The test variable is the current price/bid that i passed down from another component.

import React, { Fragment, useState } from "react";
import { connect } from "react-redux";
import { addBid } from "../../actions/listing";
import PropTypes from "prop-types";

const BidForm = ({ test, listingId, addBid }) => {
  const [price, setBid] = useState("");

  return (
    <Fragment>
      <h1 className="large text-primary">Bid</h1>

      <form
        className="form-1"
        onSubmit={e => {
          addBid(listingId, { price });
        }}
      >
        <div className="form-group pb">
          <input
            type="text"
            placeholder="Price"
            name="price"
            value={price}
            onChange={e =>
              setBid(e.target.value) & (parseFloat(price) > parseFloat(test))
                ? console.log("greater")
                : console.log("less than")
            }
          />
        </div>

        <input type="submit" className="btn btn-primary my-1" />
      </form>
    </Fragment>
  );
};

BidForm.propTypes = {
  addBid: PropTypes.func.isRequired
};

export default connect(
  null,
  { addBid }
)(BidForm);

1 Answers

setBid is not evaluated immediately, so setBid(...) && doSomethingWith(price) will use the old value of price. You need to handle the price check after the price was updated; i.e. when the component is rendered. That is, setBid will update the state, and at some point React will re-render your component. At that point, in whatever sub-component needs to know about price vs test, you are able to compare the two and render the appropriate html.

In addition, you are using the wrong operator (& instead of &&), which has the consequence:

> 2 & true
0   // this is treated at "falsy" in javascript!!

Because true (0b01) and 2 (0b10) will bit-wise & to 00.

Compare to

> 2 && true
true

You also have the prcedence wrong, and should wrap the entire ?: expression in parens:

 setBid(e.target.value) & (parseFloat(price) > parseFloat(test)
                ? console.log("greater")
                : console.log("less than"))

To illustrate:

> false && true ? 1 : 2
2
> false && (true ? 1 : 2)
false

But, fix when you compare price to test and the rest is moot.

Related