Skip to content

How to save and restore Excalidraw drawings from localStorage in React? #10255

@Mounir-abaddah

Description

@Mounir-abaddah
 
 import { Excalidraw } from "@excalidraw/excalidraw";
import "@excalidraw/excalidraw/index.css";
import { useEffect, useState } from "react";

export default function DrawExcalidraw() {
  const [elements, setElements] = useState([]);

  // Load saved drawing
  useEffect(() => {
    const savedDrawing = localStorage.getItem("drawing");
    if (savedDrawing) {
      setElements(JSON.parse(savedDrawing));
    }
  }, []);

  // Save drawing every time elements change
  useEffect(() => {
    localStorage.setItem("drawing", JSON.stringify(elements));
  }, [elements]);

  return (
    
setElements(updatedElements)} />
); }

The problem:

  • After reloading the page, the canvas is empty even though I can see the drawing data saved in localStorage.
  • Sometimes I get a JSON parse error or nothing appears on the canvas.
  • I’m not sure if I should use initialData, onChange, or other Excalidraw APIs like serialize / deserialize.

What I’ve tried :
Checked the Excalidraw documentation .

  • Tried wrapping the save and load logic inside async functions. Tried using onChange={(elements, appState) => ...} to capture both elements and app state.
  • Verified that localStorage.getItem("drawing") returns valid data.

How can I correctly save and restore Excalidraw drawings from localStorage in a React component?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions