88 lines
2.2 KiB
JavaScript
88 lines
2.2 KiB
JavaScript
import React, { useState, useEffect } from 'react';
|
|
import './App.css';
|
|
|
|
function App() {
|
|
const [notes, setNotes] = useState([]);
|
|
const [newNote, setNewNote] = useState('');
|
|
|
|
useEffect(() => {
|
|
fetchNotes();
|
|
}, []);
|
|
|
|
const fetchNotes = async () => {
|
|
try {
|
|
const response = await fetch('/api/notes');
|
|
const data = await response.json();
|
|
setNotes(data);
|
|
} catch (error) {
|
|
console.error('Ошибка при получении заметок:', error);
|
|
}
|
|
};
|
|
|
|
const addNote = async () => {
|
|
if (newNote.trim() !== '') {
|
|
try {
|
|
const response = await fetch('/api/notes', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ note: newNote }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
fetchNotes();
|
|
setNewNote('');
|
|
} else {
|
|
console.error('Не удалось добавить заметку:', data.error);
|
|
}
|
|
} catch (error) {
|
|
console.error('Ошибка при добавлении заметки:', error);
|
|
}
|
|
}
|
|
};
|
|
|
|
const deleteNote = async (index) => {
|
|
try {
|
|
const response = await fetch(`/api/notes/${index}`, {
|
|
method: 'DELETE',
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
fetchNotes();
|
|
} else {
|
|
console.error('Не удалось удалить заметку:', data.error);
|
|
}
|
|
} catch (error) {
|
|
console.error('Ошибка при удалении заметки:', error);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="App">
|
|
<h1>Заметки</h1>
|
|
<input
|
|
type="text"
|
|
value={newNote}
|
|
onChange={(e) => setNewNote(e.target.value)}
|
|
placeholder="Текст заметки..."
|
|
/>
|
|
<button onClick={addNote}>Добавить заметку</button>
|
|
<ul>
|
|
{notes.map((note, index) => (
|
|
<li key={index}>
|
|
{note}
|
|
<button onClick={() => deleteNote(index)}>Удалить</button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default App;
|