Home > Mobile >  how can i store form data as an array to localstorage in reactjs
how can i store form data as an array to localstorage in reactjs

Time:06-24

some of the states i had

  const initialValues = {companyname:"", email:"", phone:"",website:""}
  const [formValues, setFormValues] = useState(initialValues);
  const [formErrors, setFormErrors] = useState({});
  const [isSubmit, setIsSubmit] = useState(false);

trying to store form data (formValues) in localStorage on from submit to store it in it as an array but cant do it in array

 
  useEffect(()=>{
    localStorage.setItem('formValues',JSON.stringify(formValues) );
  },[formValues]);
``
[![**enter image description here**][1]][1]


  [1]: https://i.stack.imgur.com/7yprY.png

CodePudding user response:

here is the small example of your code

export default function App() {
  const [initialValues, setInitialValues] = useState({
    companyname: "",
    email: "",
    phone: "",
    website: ""
  });
  const [formValues, setFormValues] = useState([]);

  const submitForm = () => {
    setFormValues((prevFormValues) => [...prevFormValues, initialValues]);
  };

  useEffect(() => {
    localStorage.setItem("formValues", JSON.stringify(formValues));
  }, [formValues]);
  return (
    <div className="App">
      <div>
        companyname
        <input
          value={initialValues.companyname}
          onChange={(e) =>
            setInitialValues({ ...initialValues, companyname: e.target.value })
          }
        />
      </div>
      <div>
        website
        <input
          value={initialValues.website}
          onChange={(e) =>
            setInitialValues({ ...initialValues, website: e.target.value })
          }
        />
      </div>
      <button onClick={submitForm}>onSubmit </button>
    </div>
  );
}
  • Related