Refactor

mail@pastecode.io avatar
unknown
jsx
2 years ago
6.1 kB
11
Indexable
Never
import Input from "@/components/atoms/Input";
import React from "react";
import styles from "./Form.module.scss";
import form from "../../../data/global/form";
import { useState, useEffect } from "react";
import Container from "@/components/atoms/Container";
import Button from "@/components/atoms/Button";
import AddressList from "../AddressList";
import Fader from "@/components/atoms/Fader";

const Form = () => {
  const [postcode, setPostcode] = useState(null);
  const [postcodeReturned, setPostcodeReturned] = useState([]);
  const [addressList, setAddressList] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [isManual, setIsManual] = useState(false);
  const [formLast, setFormLast] = useState({});
  const formRef = React.createRef();

  const formSectionOne = React.useMemo(() => {
    if (typeof window !== "undefined") {
      
      if (localStorage.getItem("Form1")) {
        let data = JSON.parse(localStorage.getItem("Form1"));
        console.log("Form1: Retrieved:", data, "from local storage");
        console.log("");
        return form.primary.map((element) => {
          return {
            ...element,
            value: data[element.name],
          };
        });
      } else {
        console.log("Form1: Failed to retrieve data from local storage");
        return form.primary;
      }
    }
  }, []);

  const formSectionTwo = React.useMemo(() => {
    if (typeof window !== "undefined") {
      // console.log("LS: Form1", data);
      if (localStorage.getItem("Form2")) {
        let data = JSON.parse(localStorage.getItem("Form2"));
        console.log("Form2: Retrieved:", data, "from local storage");

        return form.secondary.map((element) => {
          return {
            ...element,
            value: data[element.name],
          };
        });
      } else {
        console.log("Form2: Failed to retrieve data from local storage");

        return form.secondary;
      }
    }
  }, []);
  useEffect(() => {
    console.log("re-rendered", formLast);
  }, [formSectionOne, formSectionTwo, formLast]);

  const handleFindAddress = (e) => {
    e.preventDefault();
    setIsManual(false);
    postcode != null && fetchPostcodeData(postcode);
    setAddressList(!addressList);
  };
  const handleManualAddress = () => {
    setIsManual(!isManual);
  };
  const handleFormSubmit = (e) => {
    e.preventDefault();
    let lsForm1 = JSON.parse(localStorage.getItem("Form1"));
    
    let form1 = {
      email: e.target[0].value,
      firstName: e.target[3].value,
      lastName: e.target[4].value,
      postcode: postcode
    };
    let form2 = {
      postcode: lsForm1?.postcode ||formLast?.postcode ,
      firstLine: formLast?.firstLine,
      secondLine: formLast?.secondLine,
      thirdLine: formLast?.thirdLine,
      town: formLast?.town,
      country: formLast?.country,
    };

    if (e.target[1].value !== e.target[2].value) {
      setErrorMessage("Passwords do not match, try again");
      e.target[1].style.border = "1px red solid";
      e.target[2].style.border = "1px red solid";
    } else {
      localStorage.setItem("Form1", JSON.stringify(form1));
      localStorage.setItem("Form2", JSON.stringify(form2));
    }
  };

  const handleChange = (e) => {
    setPostcode(e.target.value);
  };
  const formatData = (data) => {
    let formattedData = data?.map((val) =>
      val
        .split(",")
        .filter((x) => x.trim().length !== 0)
        .join(",")
    );
    return formattedData;
  };

  const fetchPostcodeData = (postcode) => {
    fetch(`https://api.getAddress.io/find/${postcode}?api-key=${process.env.NEXT_PUBLIC_API_URL}`)
      .then((res) => res.json())
      .then((result) => setPostcodeReturned(formatData(result.addresses)))
      .catch((error) => (setErrorMessage("Error connecting to network"), console.log(error)));
  };

  return (
    <form onSubmit={(e) => handleFormSubmit(e)} ref={formRef}>
      <section className={styles.form}>
        <Container>
          {formSectionOne?.filter(obj => obj.name !== "postcode").map((item) => (
            <Input label={item.label} type={item.type} icon={item.hasIcon} value={formLast[item.name] || item.value} name={item.name} />
          ))}
        </Container>
        {isManual ? (
          <Container>
            {formSectionTwo?.map((item) => (
              <Input label={item.label} type={item.type} icon={item.hasIcon} value={formLast[item.name] || item.value} name={item.name} />
            ))}
          </Container>
        ) : (
          <Container className={styles.postcode}>
            <Container className={styles.postcode_input}>
            {formSectionOne?.filter(obj => obj.name === "postcode").map((item) => (
              <Input label={item.label} type={item.type} icon={item.hasIcon} value={item.value || postcode} name={item.name} onChange={(e) => handleChange(e)} onClick={() => setAddressList(false)} />
            ))}
            </Container>
            <Container className={styles.postcode_button}>
              <Button label={"Find Address"} disabled={false} onClick={(e) => handleFindAddress(e)} />
            </Container>
          </Container>
        )}
        {!addressList && (
          <span onClick={handleManualAddress} className={styles.manualAddressText}>
            Enter address manually
          </span>
        )}

        {errorMessage && <Fader text={"Passwords do not match, try again..."} className={styles.error} />}
        {addressList && (
          <AddressList
            addresses={postcodeReturned}
            postcode={postcode}
            isPopulated={addressList}
            addressList={addressList}
            setIsManual={setIsManual}
            setAddressList={setAddressList}
            setFormLast={setFormLast}
          />
        )}

        <Container className={styles.signup}>
          <Button label={"Sign Up"} disabled={false} className={styles.postcode_signup} type={"submit"} />
        </Container>
      </section>
    </form>
  );
};

export default Form;