skip to Main Content

So my goal is to keep input values after user refresh page using localStorage.

I am using react-hook-form to handle whole form behavior.
I managed to target those values and save them inside localStorage so after refreshing browser input values are saved. ( I attached screenshot )


import { useForm, FormProvider } from "react-hook-form"
import InputsWrapper from "./InputsWrapper"
import Navbar from "../Navbar"
import ChoosePackage from "../ChoosePackage"
//@ts-ignore
import { Packages } from "../../types"
import axios from "axios"
import { useEffect } from "react"

interface FormData {
  name: string
  email: string
  phone: string
  city: string
  address: string
  contact_preference: string[]
  photos: Array<string | Blob>
  project_type: string
  project_level: string
  additional_info: string
  contractor: boolean | undefined
  package: Packages | undefined
}

type InquiryPayload = Omit<FormData, "photos"> & { photos: number[] }

const defaultData = {
  name: "",
  email: "",
  phone: "",
  city: "",
  address: "",
  contact_preference: [],
  photos: undefined,
  project_type: "",
  project_stage: "",
  additional_info: "",
  contractor: undefined,
  package: undefined,
}

// { phone: true, online_meeting: false} as Record<string, boolean>

const Form: React.FC = () => {
  const FormMethods = useForm<FormData>({ defaultValues: defaultData })
  const { handleSubmit, reset } = FormMethods

  useEffect(() => {
    const savedFormData = localStorage.getItem("formData")
    if (savedFormData) {
      const parsedFormData = JSON.parse(savedFormData)
      reset(parsedFormData)
    }
  }, [])

  useEffect(() => {
    const saveFormData = JSON.stringify(FormMethods.getValues())
    localStorage.setItem("formData", saveFormData)
  }, [FormMethods.watch()])

  const onFormSubmit = async (data: FormData) => {
    const token =
      "*********************"
    let formData = new FormData()
    Object.values(data.photos).forEach((photo: string | Blob) =>
      formData.append("files", photo)
    )

    try {
      const res = await axios({
        method: "POST",
        url: "https://strapi-km.herokuapp.com/api/upload",
        data: formData,
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      const photoIds: number[] = res.data.map((e: { id: number }) => e.id)
      let dataCopy: InquiryPayload = { ...data, photos: photoIds }

      const response = await axios({
        method: "POST",
        url: "https://strapi-km.herokuapp.com/api/inquiries",
        data: { data: dataCopy },
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
      window.alert("Form has been submitted !")
      console.log("Inquiry", response.data)
    } catch (error) {
      console.log(error)
    }
    localStorage.removeItem("formData")
    reset()
  }

  return (
    <>
      <div className="bg-gray-50">
        <Navbar />
        <FormProvider {...FormMethods}>
          <form onSubmit={handleSubmit(onFormSubmit)}>
            <div>
              <ChoosePackage />
              <InputsWrapper />
              <div className="mx-10">
                <button
                  className="transition-colors duration-300 w-full mb-5 tracking-widest text-2xl border border-black text-gray-50 p-2 hover:bg-indigo-100 hover:text-indigo-900 bg-indigo-800"
                  type="submit"
                >
                  SUBMIT
                </button>
              </div>
            </div>
          </form>
        </FormProvider>
      </div>
    </>
  )
}

export default Form

enter image description here

Issue is that after form submit I want to clear localStorage to make inputs clear once again ( for example if someone would like to submit another form ). Don’t know why but

localStorage.removeItem("formData") and localStorage.clear() doesn’t work…

I tried also to call it after Form has been submitted or after reset() but it also didn’t solve the problem.

If someone could help me and explain that issue I would really appreciate any help 🙂

2

Answers


  1. Have you tried reloading the page after you clear or remove the items from localStorage.

    Login or Signup to reply.
  2. have you tried this :

    function deleteItems() {
      sessionStorage.clear();
    }
    

    from w3school

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search