Added Sidebar
This commit is contained in:
51
src/contexts/NotesStore.tsx
Normal file
51
src/contexts/NotesStore.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { createContext, useContext, useState, ReactNode, useEffect } from "react";
|
||||
import { Note } from "../models/Note"
|
||||
|
||||
type NotesStoreType = {
|
||||
notes: Note[];
|
||||
createNote: () => void;
|
||||
updateNote: (noteId: string, changeset: Partial<Note>) => void;
|
||||
deleteNote: (noteId: string) => void;
|
||||
getNoteById: (noteId: string) => Note;
|
||||
}
|
||||
|
||||
const NotesStore = createContext<NotesStoreType | null>(null);
|
||||
|
||||
export function NotesStoreProvider({ children }: { children: ReactNode }) {
|
||||
const [notes, setNotes] = useState<Note[]>([]);
|
||||
|
||||
const createNote = () => {
|
||||
const newNote = new Note();
|
||||
setNotes([...notes, newNote]);
|
||||
return newNote;
|
||||
}
|
||||
|
||||
const updateNote = (noteId: string, changeset: Partial<Note>) => {
|
||||
setNotes(notes.map(note =>
|
||||
note.id === noteId ? new Note({ ...note, ...changeset }) : note
|
||||
))
|
||||
}
|
||||
|
||||
const deleteNote = (noteId: string) => {
|
||||
setNotes(notes.filter(note => note.id !== noteId))
|
||||
}
|
||||
|
||||
const getNoteById = (noteId: string) => {
|
||||
return notes.find(note => note.id === noteId);
|
||||
}
|
||||
|
||||
return (
|
||||
<NotesStore.Provider value={{ notes, createNote, updateNote, deleteNote, getNoteById }}>
|
||||
{children}
|
||||
</NotesStore.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useNotesStore() {
|
||||
const context = useContext(NotesStore)
|
||||
if (!context) {
|
||||
throw new Error("useNotesStore must be used from within NotesStoreProvider")
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user