Skip to content

Feature: Implement LocalStorage Persistence for Code Drafts #492

@rishabh0510rishabh

Description

@rishabh0510rishabh

1. Problem Statement

Currently, the application relies solely on in-memory state management for the code editor. This poses a significant risk to user experience: if a user accidentally refreshes the page, closes the tab, or experiences a browser crash, their uncommitted code is irretrievably lost. This lack of persistence negatively impacts the perceived reliability of the platform.

2. Current Behavior / Limitation

  • The editor state is initialized to default values on every component mount.
  • Code changes are stored only in the React state (EditorContext).
  • There is no background synchronization to the browser's persistent storage.
  • Result: A page reload results in total data loss of the current working session.

3. Expected Improvement

To protect user work, the application should implement a local persistence layer.

  • The editor should automatically save the current code state to localStorage at specific intervals or on change.
  • Upon reloading the application, if a saved draft is detected that differs from the default template, the user should be presented with a "Recover Draft" UI option (or auto-recovery depending on UX preference) to restore their previous work.

4. Proposed Approach

This feature involves creating a utility hook, updating the global context, and adding a UI indicator.

Technical Steps:

A. Create/Update Utility Hook (src/hooks/useLocalStorage.js)

  • Implement a custom hook that handles:
    • Safe serialization (JSON.stringify) and deserialization (JSON.parse) of data.
    • Error handling for quota limits or disabled storage.
    • Synchronization logic to keep React state and LocalStorage in sync.

B. Integrate with Editor Logic (src/context/EditorContext.jsx)

  • Import useLocalStorage.
  • Implement a debounced save mechanism (e.g., save 1 second after the user stops typing) to prevent performance bottlenecks.
  • On EditorContext mount, check for the existence of a saved key (e.g., justcoding_draft_v1).
  • If data exists, set a flag (e.g., hasSavedDraft) to true.

C. UI Implementation (src/components/Editor/DraftStatus.jsx)

  • Create a component to display the current status (e.g., "Saving...", "Saved locally").
  • Implement the Recover Draft flow:
    • If hasSavedDraft is true on load, display a toast or banner asking the user: "We found an unsaved draft. Would you like to recover it?"
    • On confirmation, load data from LS into the Editor state.
    • On dismissal, clear the specific key from LS.
      Labels: ECWoC26

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions