To make the data in the input field of your form in Next.js stay after a page refresh, you can use browser storage mechanisms such as Local Storage or Session Storage to store and retrieve the form data. These storage options allow you to persist data across page refreshes and even browser sessions.

Here's how you can achieve this:

  1. Save Form Data to Local Storage: In your form component, you can use JavaScript to save the form data to Local Storage whenever the input value changes or when the form is submitted.

    jsx
    // FormComponent.js import { useState } from 'react'; const FormComponent = () => { const [formData, setFormData] = useState({ // Initialize form data with values from Local Storage name: localStorage.getItem('name') || '', email: localStorage.getItem('email') || '', // Add other form fields here }); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); // Save the updated form data to Local Storage localStorage.setItem(name, value); }; const handleSubmit = (e) => { e.preventDefault(); // Process form submission here // Optionally, you can clear the form data after submission setFormData({ name: '', email: '' }); localStorage.removeItem('name'); localStorage.removeItem('email'); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="name" value={formData.name} onChange={handleChange} placeholder="Name" /> <input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Email" /> <button type="submit">Submit</button> </form> ); }; export default FormComponent;
  2. Retrieve Data from Local Storage on Page Load: When the page loads, you can retrieve the form data from Local Storage and initialize the form state with the stored values.

    jsx
    // pages/index.js (or any other page that contains the form) import FormComponent from '../path/to/FormComponent'; const HomePage = () => { return ( <div> <h1>Form Example</h1> <FormComponent /> </div> ); }; export default HomePage;

With this setup, when a user enters data in the form and refreshes the page, the form fields will be populated with the data previously entered. The data is retrieved from Local Storage and used to initialize the form state when the page loads.

Keep in mind that data stored in Local Storage remains available even after the user closes and reopens the browser. If you want the data to persist only during a session (until the browser is closed), you can use Session Storage instead of Local Storage.

Remember that Local Storage and Session Storage have limitations on the amount of data that can be stored (typically around 5-10 MB), and they are specific to each domain. Additionally, be mindful of sensitive data and avoid storing any sensitive information in browser storage mechanisms.

Have questions or queries?
Get in Touch