Untitled
unknown
jsx
2 years ago
5.9 kB
3
Indexable
Never
const Form = ({ setFormLoading }) => { 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 [values, setValues] = useState(initialValues); const handleInputChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value, }); }; // A helper function to create dyanamic useMemo hooks const createFormMemo = (localStorageName, dataVariable) => { return React.useMemo(() => { if (typeof window !== "undefined") { if (localStorage.getItem(localStorageName)) { let data = JSON.parse(localStorage.getItem(localStorageName)); console.log(`${localStorageName} Retrieved:", ${data}`); return dataVariable.map((element) => { return { ...element, value: data[element.name], }; }); } else { console.log(`${localStorageName}: Failed to retrieve data...`); return dataVariable; } } }, []); }; // Handles the fine address button onClick const handleFindAddress = (e) => { e.preventDefault(); setIsManual(false); // if values.postcode exists & is not null, pass values.postcode to fetchPostcode values.postcode != null && fetchPostcode(values.postcode); setAddressList(!addressList); }; const handleSignUp = (e) => { e.preventDefault(); if (values.password !== values.verifyPassword) { 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({ email: values.email, first: values.first, last: values.last, postcode: values.postcode }) ); localStorage.setItem( "Form2", JSON.stringify({ postcode: values.postcode, address1: formLast.address1, address2: values.secondLine, address3: values.thirdLine, town: formLast?.town, country: formLast?.country, }) ); setFormLoading(true); setTimeout(() => { setFormLoading(false); Router.push("/verify"); }, 1750); clearTimeout(); } }; const fetchPostcode = (postcode) => { // Fetch postcode with postcode as parameter fetch(`https://api.getAddress.io/find/${postcode}?api-key=${process.env.NEXT_PUBLIC_API_URL}`) .then((res) => res.json()) .then((result) => // store result inside postcodeReturned state setPostcodeReturned( result.addresses.map((val) => val .split(",") .filter((x) => x.trim().length !== 0) .join(",") ) ) ) .catch((error) => (setErrorMessage("Error connecting to network"), console.log(error))); }; return ( <form onSubmit={(e) => handleSignUp(e)} ref={formRef}> <section className={styles.form}> <Container> {createFormMemo("Form1", form.primary) ?.filter((obj) => obj.name !== "postcode") .map((item) => ( <Input label={item.label} type={item.type} icon={item.hasIcon} value={values[item.name] || item.value} name={item.name} onChange={handleInputChange} /> ))} </Container> {isManual ? ( <Container> {createFormMemo("Form2", form.secondary)?.map((item) => ( <Input label={item.label} type={item.type} icon={item.hasIcon} value={formLast[item.name] || item.value} name={item.name} onChange={handleInputChange} /> ))} </Container> ) : ( <Container className={styles.postcode}> <Container className={styles.postcode_input}> {createFormMemo("Form2", form.secondary) ?.filter((obj) => obj.name === "postcode") .map((item) => ( <Input label={item.label} type={item.type} icon={item.hasIcon} value={values.postcode || item.value} name={item.name} onChange={handleInputChange} onClick={() => setAddressList(false)} /> ))} </Container> <Container className={styles.postcode_button}> <Button label={"Find Address"} disabled={false} onClick={(e) => handleFindAddress(e)} /> </Container> </Container> )} {!addressList && ( <span onClick={() => setIsManual(!isManual)} className={styles.manualAddressText}> Enter address manually </span> )} {errorMessage && <Fader text={"Passwords do not match, try again..."} className={styles.error} />} {addressList && ( <AddressList addresses={postcodeReturned} postcode={values.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;