UX mejoras
This commit is contained in:
35
src/App.jsx
35
src/App.jsx
@@ -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}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user