diff --git a/src/App.tsx b/src/App.tsx index cbdd5a4..57d6ad7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -27,8 +27,13 @@ const App = () => { useEffect(() => { // Vérifier le token au démarrage const checkAuth = async () => { - const isValid = await AuthService.checkTokenValidity(); - setIsLoading(false); + try { + await AuthService.checkTokenValidity(); + } catch (error) { + console.error("Error checking token validity:", error); + } finally { + setIsLoading(false); + } }; checkAuth(); diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 531ac2d..7ac0d5c 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -13,36 +13,44 @@ import AdminService from "@/services/AdminService"; import NotesService, { Note } from "@/services/NotesService"; import { useNavigate } from "react-router-dom"; +interface UserType { + id: number; + username: string; + is_admin: boolean; +} + const Index = () => { - const [user, setUser] = useState(null); + const [user, setUser] = useState(null); const [showAdmin, setShowAdmin] = useState(false); const [activeTab, setActiveTab] = useState("all"); const [searchQuery, setSearchQuery] = useState(""); const [notes, setNotes] = useState([]); const [currentNote, setCurrentNote] = useState(null); - const [users, setUsers] = useState([]); + const [users, setUsers] = useState([]); const navigate = useNavigate(); useEffect(() => { - const user = AuthService.getUser(); - if (user) { - setUser(user); + const userFromAuth = AuthService.getUser(); + if (userFromAuth) { + setUser(userFromAuth); loadNotes(); + } else { + navigate("/login"); } - }, []); + }, [navigate]); const loadNotes = async () => { - const notes = await NotesService.getNotes(); - setNotes(notes); - if (notes.length > 0) { - setCurrentNote(notes[0]); + const fetchedNotes = await NotesService.getNotes(); + setNotes(fetchedNotes || []); + if (fetchedNotes && fetchedNotes.length > 0) { + setCurrentNote(fetchedNotes[0]); } }; const loadUsers = async () => { if (user?.is_admin) { - const users = await AdminService.getUsers(); - setUsers(users); + const fetchedUsers = await AdminService.getUsers(); + setUsers(fetchedUsers || []); } }; @@ -62,7 +70,13 @@ const Index = () => { const handleUpdateNote = async (updatedFields: Partial) => { if (!currentNote) return; - const updatedNote = { ...currentNote, ...updatedFields }; + const updatedNote = { + ...currentNote, + ...updatedFields, + todos: currentNote.todos || [], + images: currentNote.images || [] + }; + const success = await NotesService.updateNote(updatedNote); if (success) { @@ -137,7 +151,7 @@ const Index = () => { (activeTab === "all" || (activeTab === "archived" && note.archived)) && (searchQuery === "" || note.title.toLowerCase().includes(searchQuery.toLowerCase()) || - note.content.toLowerCase().includes(searchQuery.toLowerCase())) + (note.content && note.content.toLowerCase().includes(searchQuery.toLowerCase()))) ); return ( @@ -165,33 +179,35 @@ const Index = () => {
- - - - - - Mon compte - - {user?.is_admin && ( - setShowAdmin(true)}> - - Administration + {user && ( + + + + + + Mon compte + + {user.is_admin && ( + setShowAdmin(true)}> + + Administration + + )} + + + Déconnexion - )} - - - Déconnexion - - - + + + )}
@@ -259,7 +275,7 @@ const Index = () => { type="text" placeholder="Titre de la note" className="text-xl font-semibold border-none shadow-none text-2xl h-auto px-0 focus-visible:ring-0" - value={currentNote.title} + value={currentNote.title || ""} onChange={(e) => handleUpdateNote({ title: e.target.value })} /> @@ -295,7 +311,7 @@ const Index = () => { className="min-h-[500px] outline-none" contentEditable suppressContentEditableWarning - dangerouslySetInnerHTML={{ __html: currentNote.content }} + dangerouslySetInnerHTML={{ __html: currentNote.content || "" }} onBlur={(e) => handleUpdateNote({ content: e.currentTarget.innerHTML })} /> @@ -331,7 +347,7 @@ const Index = () => { type="checkbox" checked={todo.completed} onChange={() => { - const updatedTodos = [...currentNote.todos]; + const updatedTodos = [...(currentNote.todos || [])]; updatedTodos[index].completed = !updatedTodos[index].completed; handleUpdateNote({ todos: updatedTodos }); }} @@ -345,7 +361,7 @@ const Index = () => { size="icon" className="ml-auto h-6 w-6" onClick={() => { - const updatedTodos = [...currentNote.todos]; + const updatedTodos = [...(currentNote.todos || [])]; updatedTodos.splice(index, 1); handleUpdateNote({ todos: updatedTodos }); }} @@ -412,7 +428,7 @@ const Index = () => { if (image.id && currentNote.id) { const success = await NotesService.deleteImage(currentNote.id, image.id); if (success) { - const updatedImages = currentNote.images.filter((_, i) => i !== index); + const updatedImages = (currentNote.images || []).filter((_, i) => i !== index); handleUpdateNote({ images: updatedImages }); } } diff --git a/src/services/AuthService.ts b/src/services/AuthService.ts index adc52bf..c1c0468 100644 --- a/src/services/AuthService.ts +++ b/src/services/AuthService.ts @@ -30,7 +30,7 @@ class AuthService { getHeaders(): Record { return { - "Authorization": `Bearer ${this.token}`, + "Authorization": `Bearer ${this.token || ""}`, "Content-Type": "application/json" }; } @@ -51,8 +51,8 @@ class AuthService { this.token = data.token; this.user = data.user; - localStorage.setItem("token", this.token); - localStorage.setItem("user", JSON.stringify(this.user)); + localStorage.setItem("token", this.token || ""); + localStorage.setItem("user", JSON.stringify(this.user || {})); showSuccess("Connexion réussie"); return true; diff --git a/src/services/NotesService.ts b/src/services/NotesService.ts index fbde5a6..aa5fe61 100644 --- a/src/services/NotesService.ts +++ b/src/services/NotesService.ts @@ -35,7 +35,14 @@ class NotesService { throw new Error("Erreur lors de la récupération des notes"); } - return await response.json(); + const notes = await response.json(); + + // Ensure todos and images are always arrays + return notes.map((note: Note) => ({ + ...note, + todos: note.todos || [], + images: note.images || [] + })); } catch (error) { showError(error instanceof Error ? error.message : "Erreur serveur"); return []; @@ -55,7 +62,12 @@ class NotesService { } showSuccess("Note créée avec succès"); - return await response.json(); + const note = await response.json(); + return { + ...note, + todos: note.todos || [], + images: note.images || [] + }; } catch (error) { showError(error instanceof Error ? error.message : "Erreur serveur"); return null; @@ -69,7 +81,11 @@ class NotesService { const response = await fetch(`/api/notes/${note.id}`, { method: "PUT", headers: AuthService.getHeaders(), - body: JSON.stringify(note) + body: JSON.stringify({ + ...note, + todos: note.todos || [], + images: note.images || [] + }) }); if (!response.ok) {