UX mejoras
All checks were successful
build-and-deploy / build (push) Successful in 10s
build-and-deploy / deploy (push) Successful in 14s

This commit is contained in:
2025-09-06 18:06:36 -06:00
parent 7a5bd7f78e
commit bee018fdc9
3 changed files with 123 additions and 2 deletions

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef } from 'react'
import './App.css'
// Configure API base URL via Vite env, default to same-origin
@@ -9,11 +9,34 @@ function App() {
const [amigos, setAmigos] = useState([])
const [loading, setLoading] = useState(false)
const [message, setMessage] = useState('')
const inputRef = useRef(null)
useEffect(() => {
fetchAmigos()
// Conectar a SSE para cambios en tiempo real
connectSSE()
}, [])
const connectSSE = () => {
const eventSource = new EventSource(`${API_BASE}/api/stream`)
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data)
if (data.type === 'amigo_added') {
setAmigos(prevAmigos => [...prevAmigos, data.amigo])
}
}
eventSource.onerror = (error) => {
console.error('SSE error:', error)
eventSource.close()
// Reconectar después de 3 segundos
setTimeout(connectSSE, 3000)
}
return () => eventSource.close()
}
const fetchAmigos = async () => {
try {
const response = await fetch(`${API_BASE}/api/amigos`)
@@ -49,7 +72,9 @@ function App() {
if (response.ok) {
setMessage(`¡${data.nombre} agregado exitosamente!`)
setNombre('')
fetchAmigos()
// Ya no necesitamos fetchAmigos() porque SSE actualizará automáticamente
// Mantener focus en el input
inputRef.current?.focus()
} else {
setMessage(data.error || 'Error al agregar amigo')
}
@@ -69,10 +94,16 @@ function App() {
<div className="form-group">
<label htmlFor="nombre">Nombre del amigo:</label>
<input
ref={inputRef}
type="text"
id="nombre"
value={nombre}
onChange={(e) => setNombre(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !loading) {
handleSubmit(e)
}
}}
placeholder="Ingresa el nombre"
disabled={loading}
/>