/*import React, { useState, useEffect } from "react";
const App = () => {
const [notes, setNotes] = useState([]);
const [newNote, setNewNote] = useState("");
useEffect(() => {
fetch("/api/notes", { method: "GET" })
.then((res) => res.json())
.then((data) => setNotes(data.notes))
.catch((err) => console.error(err));
}, []);
const handleAddNote = () => {
fetch("/api/notes", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ content: newNote }),
})
.then((res) => res.json())
.then((data) => {
console.log(data.message);
setNewNote("");
// Refresh notes after adding a new one
fetch("/api/notes")
.then((res) => res.json())
.then((data) => setNotes(data.notes))
.catch((err) => console.error(err));
})
.catch((err) => console.error(err));
};
return (
<div>
<h1>Express and React Example</h1>
<ul>
{notes.map((note) => (
<li key={note._id}>{note.content}</li>
))}
</ul>
<input
type="text"
placeholder="Add a new note"
value={newNote}
onChange={(e) => setNewNote(e.target.value)}
/>
<button onClick={handleAddNote}>Add Note</button>
</div>
);
};
export default App;
*/
import React, { useState, useEffect } from "react";
/**
* Functional component representing the main application.
* @function
* @component
*/
const App = () => {
/**
* State to store the array of notes.
* @type {Array<Object>}
*/
const [notes, setNotes] = useState([]);
/**
* State to store the content of a new note.
* @type {string}
*/
const [newNote, setNewNote] = useState("");
/**
* Effect hook to fetch notes from the server on component mount.
* @function
* @name useEffect
* @param {Function} effect - The function to execute.
* @param {Array} dependencies - The dependencies to watch for changes.
*/
useEffect(() => {
fetch("/api/notes", { method: "GET" })
.then((res) => res.json())
.then((data) => setNotes(data.notes))
.catch((err) => console.error(err));
}, []);
/**
* Handler function to add a new note.
* @function
* @name handleAddNote
*/
const handleAddNote = () => {
fetch("/api/notes", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ content: newNote }),
})
.then((res) => res.json())
.then((data) => {
console.log(data.message);
setNewNote("");
// Refresh notes after adding a new one
fetch("/api/notes")
.then((res) => res.json())
.then((data) => setNotes(data.notes))
.catch((err) => console.error(err));
})
.catch((err) => console.error(err));
};
/**
* Render function.
* @returns {JSX.Element} The JSX representation of the component.
*/
return (
<div>
<h1>Express and React Example</h1>
<ul>
{notes.map((note) => (
<li key={note._id}>{note.content}</li>
))}
</ul>
<input
type="text"
placeholder="Add a new note"
value={newNote}
onChange={(e) => setNewNote(e.target.value)}
/>
<button onClick={handleAddNote}>Add Note</button>
</div>
);
};
export default App;