34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
import { useCallback, useEffect, useMemo, useState } from 'react'
|
|
import type { Note } from '../types'
|
|
import { loadNotes, saveNotes } from '../lib/notesStorage'
|
|
|
|
export function useNotes() {
|
|
const [notes, setNotes] = useState<Note[]>(() => loadNotes())
|
|
|
|
useEffect(() => {
|
|
saveNotes(notes)
|
|
}, [notes])
|
|
|
|
const addNote = useCallback((title = '', content = '') => {
|
|
const note: Note = { id: Date.now(), title, content }
|
|
setNotes((current) => [...current, note])
|
|
return note
|
|
}, [])
|
|
|
|
const updateNote = useCallback((id: number, patch: Partial<Pick<Note, 'title' | 'content'>>) => {
|
|
setNotes((current) => current.map((note) => (note.id === id ? { ...note, ...patch } : note)))
|
|
}, [])
|
|
|
|
const deleteNote = useCallback((id: number) => {
|
|
setNotes((current) => current.filter((note) => note.id !== id))
|
|
}, [])
|
|
|
|
const sortedNotes = useMemo(
|
|
() =>
|
|
[...notes].sort((a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: 'base' })),
|
|
[notes],
|
|
)
|
|
|
|
return { notes: sortedNotes, addNote, updateNote, deleteNote }
|
|
}
|