Skip to content

Commit

Permalink
Refactored: added function + types + error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Suraj-Ram committed Oct 30, 2024
1 parent 269f233 commit 70e1884
Showing 1 changed file with 33 additions and 13 deletions.
46 changes: 33 additions & 13 deletions packages/frontend/components/Sidebar/SandboxArea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {
} from "@chakra-ui/react";
import { forwardRef, useEffect, useState } from "react";
import ResizeTextarea from "react-textarea-autosize";
import { toast } from "react-toastify";

// Still a bit buggy
const AutoResizeTextarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
(props, ref) => {
return (
Expand All @@ -33,28 +33,48 @@ interface SandboxAreaProps {
planId: string | number;
}

type StoredNotes = {
[planId: string]: string;
};

function getStoredNotes(): StoredNotes {
const storedNotes = localStorage.getItem("notes");
if (!storedNotes) {
return {};
}

return JSON.parse(storedNotes);
}

function setStoredNotes(notes: StoredNotes) {
try {
localStorage.setItem("notes", JSON.stringify(notes));
} catch (e) {
toast.error("Maximum local storage quota exceed. Too many plans.");
}
}

function getPlanNote(planId: string): string {
const notesObject = getStoredNotes();
return notesObject[planId] || "";
}

export const SandboxArea: React.FC<SandboxAreaProps> = ({ planId }) => {
const [notes, setNotes] = useState<string>("");

const handleNewNotes = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
if (!planId) return;
setNotes(e.target.value);
// Retrieve existing notes from localStorage
const storedNotes = localStorage.getItem("notes");
const notesObject = storedNotes ? JSON.parse(storedNotes) : {};
notesObject[planId] = notes;
// have a notes object plan_id (number | string) -> note (string)
localStorage.setItem("notes", JSON.stringify(notesObject));
//console.log("New notes: ", e.target.value);
const notesObj = getStoredNotes();
notesObj[planId] = e.target.value;
setStoredNotes(notesObj);
};

useEffect(() => {
if (!planId) return;
const storedNotes = localStorage.getItem("notes");
const notesObject = storedNotes ? JSON.parse(storedNotes) : {};
if (storedNotes) {
setNotes(notesObject[planId]);
}
setNotes(getPlanNote(String(planId)));
}, [planId]);

return (
<Box backgroundColor="white" pt="6" pb="6" px="3">
<VStack align="left" px="4">
Expand Down

0 comments on commit 70e1884

Please sign in to comment.