richardC
richardC

Reputation: 63

Reset Input Fields - Keep printed state on screen

I have an AWS app and I am having difficulty resetting the form fields.

The app sends an image to s3 and to textract. Textract reads the image and takes values off it. I have a lambda function that then checks to see if values that I send with the image are contained in the image i.e does the image contain the numbers 1234567E. It returns true or false.

So when it returns true I want to append "Value Matched - ${ppsn} found!" at the bottom of the screen. I have gotten this working but if I clear the input fields using useEffect for example, it changes the appended text at the bottom of the screen to say "Value Matched - "" found! the fact that "" is now the state for the input field it also triggers my appended text "Value not matched - no value entered in the field".

Essentially, I need to have the number printed on the screen while also being able to change state for the number back to zero (without affecting the number appended at the end of the screen). Any help is appreciated!

function Upload(props) {
  const [confirmation, setConfirmation] = useState("");
  const [, setFiles] = useState("");
  const [, setLambdaReturn] = useState("");
  const [ppsnPresent, setPpsnPresent] = useState(false);
  const [lastNamePresent, setLastNamePresent] = useState(false);
  const [firstNamePresent, setFirstNamePresent] = useState(false);
  const [disabled, setDisabled] = useState(true);
  const [dropDownOpen, setDropDownOpen] = useState(false);
  const [dropDownValue, setDropDownValue] = useState("");
  const [invoiceUploaded, setInvoiceUploaded] = useState("Upload Document");
  const [ocrSuccess, setOcrSuccess] = useState(false);
  const [refreshPage, setRefreshPage] = useState(false);
  const [formValues, setFormValues] = useState({
    ppsn: "",
    firstName: "",
    lastName: "",
  });

  const { ppsn, firstName, lastName } = formValues;

  const handleChange = (e) => {
    e.preventDefault();
    const { name, value } = e.target;
    setFormValues({ ...formValues, [name]: value });
  };
  // PPSN VALIDATION
  const _onKeyUp = () => {
    let regex = /[0-9]{7}[A-Za-z]{1}$/g;
    ppsn.match(regex) ? setDisabled(false) : setDisabled(true);
  };

  // DROPDOWN SELECTION
  const toggle = () => {
    dropDownOpen === false ? setDropDownOpen(true) : setDropDownOpen(false);
  };

  const selectDD = (e) => {
    setDropDownValue(e.currentTarget.textContent);
  };

  const dropDownMessage =
    dropDownValue !== "" ? dropDownValue : "Select Document Type";

  // API CALL TO AWS S3 & LAMBDA

  const getFiles = async (files) => {
    setFiles(files);
    // setConfirmation("Scanning");

    const UID = Math.round(1 + Math.random() * (1000000 - 1));
    const { ppsn, firstName, lastName } = formValues;
    var data = {
      fileExt: "png",
      imageID: UID,
      folder: UID,
      ppsn,
      firstName,
      lastName,
      img: files.base64,
    };

    await axios(
      "S3 Link",
      {
        method: "POST",
        data,
      }
    )
      .then((res) => {
        console.log("s3", res);
        setInvoiceUploaded(
          `${dropDownValue !== "N/A" ? dropDownValue : "Document"} Uploaded`
        );
      })
      .catch((error) => {
        console.log(error);
      });

    axios(
      "Textract Link",
      {
        method: "POST",
        data,
      }
    )
      .then((res) => {
        console.log("OCR", res);
        const response = res.data.body;

        setLambdaReturn(response[0]);
        setOcrSuccess(true);

        const { ppsn, firstName, lastName } = formValues;
        ppsn !== "" && setPpsnPresent(response[1]);
        firstName !== "" && setFirstNamePresent(response[2]);
        lastName !== "" && setLastNamePresent(response[3]);

        // setConfirmation("");
      })

      .catch((error) => {
        console.log(error);
        alert("Please refresh the browser and try again");
      });
  };

  //DISPLAYS PPSN/NAME MATCH RESULTS

  const ppsnMatchDisplayTrue =
    ppsnPresent && ocrSuccess && `PPSN: ${ppsn} - Matched`;

  const ppsnMatchDisplayFalse =
    ppsnPresent !== true && ocrSuccess && `PPSN: ${ppsn} - Not Matched`;

  const ppsnMatchDisplayEmpty =
    ocrSuccess && ppsn === "" && `PPSN Not Provided`;

  const lastNameMatchDisplayTrue =
    lastNamePresent && ocrSuccess && `Last Name: "${lastName}" - Matched`;

  const lastNameMatchDisplayFalse =
    lastNamePresent !== true &&
    ocrSuccess &&
    lastName !== "" &&
    `Last Name: "${lastName}" - Not Matched`;

  const lastNameMatchDisplayEmpty =
    ocrSuccess && lastName === "" && `Last Name Not Provided`;

  const firstNameMatchDisplayTrue =
    firstNamePresent && ocrSuccess && `First Name: "${firstName}" - Matched`;

  const firstNameMatchDisplayFalse =
    firstNamePresent !== true &&
    ocrSuccess &&
    lastName !== "" &&
    `First Name: "${firstName}" - Not Matched`;

  const firstNameMatchDisplayEmpty =
    ocrSuccess && firstName === "" && "First Name Not Provided";

  //LOADING MESSAGES
  const searchingDocumentMessage =
    invoiceUploaded === `${dropDownValue} Uploaded` &&
    ocrSuccess === false &&
    "Searching Document";

  const uploadDocumentMessage =
    dropDownValue !== "N/A" || "" ? dropDownValue : "file";

  useEffect(() => {
    if (
      ppsnMatchDisplayTrue ||
      ppsnMatchDisplayFalse ||
      ppsnMatchDisplayEmpty
    ) {
      setFormValues({ ppsn: "" });
    }

    console.log("useeffect");
    console.log(refreshPage);
  }, [
    refreshPage,
    ppsnMatchDisplayEmpty,
    ppsnMatchDisplayFalse,
    ppsnMatchDisplayTrue,
  ]);

  return (
    <div className="container" style={styles.marginTop10}>
      <div className="mt-3">
        <div>
          <Form>
            <FormGroup>
              <Label for="ppsn" style={styles.marginTop10}>
                <h5 style={styles.boiText}>
                  {" "}
                  PPSN <span style={{ color: "red" }}> * </span>
                </h5>
                <Input
                  style={styles.width300}
                  type="text"
                  name="ppsn"
                  id="ppsn"
                  placeholder="(e.g. 1234567P)"
                  onChange={handleChange}
                  onKeyUp={_onKeyUp}
                  value={formValues.ppsn}
                />
              </Label>
            </FormGroup>

            <FormGroup>
              <Label for="lastName">
                <h5 style={styles.boiText}> LAST NAME</h5>
                <Input
                  style={styles.width300}
                  type="text"
                  name="lastName"
                  id="lastName"
                  placeholder="(Bloggs)"
                  onChange={handleChange}
                  disabled={disabled}
                  value={formValues.lastName}
                />
              </Label>
            </FormGroup>
            <FormGroup>
              <Label for="firstName">
                <h5 style={styles.boiText}> FIRST NAME </h5>
                <Input
                  style={styles.width300}
                  type="text"
                  name="firstName"
                  id="firstName"
                  placeholder="(Joe)"
                  onChange={handleChange}
                  disabled={disabled}
                  value={formValues.firstName}
                />
              </Label>
            </FormGroup>

            <Dropdown isOpen={dropDownOpen} toggle={toggle}>
              <DropdownToggle style={styles.boiButton} caret>
                {dropDownMessage}
              </DropdownToggle>
              <DropdownMenu>
                <DropdownItem header>
                  P60/Payslip/Revenue Letter/Social Welfare
                </DropdownItem>
                <DropdownItem onClick={selectDD} style={styles.boiButton}>
                  P60
                </DropdownItem>
                <DropdownItem onClick={selectDD} style={styles.boiButton}>
                  Payslip
                </DropdownItem>

                <DropdownItem onClick={selectDD} style={styles.boiButton}>
                  Revenue Document
                </DropdownItem>
                <DropdownItem onClick={selectDD} style={styles.boiButton}>
                  Social Welfare Letter
                </DropdownItem>
                <DropdownItem onClick={selectDD} style={styles.boiButton}>
                  N/A
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>

            <FormGroup>
              <h3 className="text-danger"> {confirmation} </h3>
              <h4 style={styles.boiText}> {invoiceUploaded}</h4>
              <h4 className="text-danger">{searchingDocumentMessage}</h4>
              <FormText color="muted"> PNG, JPG </FormText> <br />
              <br />
              <div className="width upload-btn-wrapper ">
                <button className="btn width">
                  Upload {uploadDocumentMessage}
                </button>
                <FileBase64 className="width" mulitple={true} onDone={getFiles}>
                  {" "}
                </FileBase64>
              </div>
            </FormGroup>

            <div style={styles.boiText}>
              {ppsnMatchDisplayTrue}
              {ppsnMatchDisplayFalse}
              {ppsnMatchDisplayEmpty} <br />
              {lastNameMatchDisplayTrue}
              {lastNameMatchDisplayFalse}
              {lastNameMatchDisplayEmpty} <br />
              {firstNameMatchDisplayEmpty}
              {firstNameMatchDisplayFalse}
              {firstNameMatchDisplayTrue}
              <br />
            </div>
          </Form>
    </div>
  </div>
</div>

); }

export default Upload;

Upvotes: 0

Views: 37

Answers (1)

richardC
richardC

Reputation: 63

Solution for anyone else who is stuck. As the printed value on the screen was from state taken from the input fields, when i reset the values in the input it reset the state and printed "". So what I did was in the response from the api call, it contained the data that was sent to the API originally. I created a variable for the form field data that was returned with the api call and set this to a variable called originalState (for eg) and then printed originalState on the screen which allowed the input fields to be reset without messing up the appended text on the screen.

Upvotes: 0

Related Questions