RN Lez 24: fetch POST e WebSocket
Docs: Network
Obiettivi
Section titled “Obiettivi”- Fare chiamate POST con body JSON
- Gestire errori di rete robustamente
- Usare WebSocket per comunicazione实时
1. POST — inviare dati
Section titled “1. POST — inviare dati”const creaPost = async (titolo: string, corpo: string) => { try { const res = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: titolo, body: corpo, userId: 1, }), }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json(); console.log('Creato con ID:', data.id); return data; } catch (err) { console.error('Errore:', err); throw err; }};2. Pattern: form che invia dati
Section titled “2. Pattern: form che invia dati”const [titolo, setTitolo] = useState('');const [corpo, setCorpo] = useState('');const [salvataggio, setSalvataggio] = useState(false);
const invia = async () => { if (!titolo || !corpo) { Alert.alert('Errore', 'Compila tutti i campi'); return; }
setSalvataggio(true); try { const res = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: titolo, body: corpo, userId: 1 }), }); if (!res.ok) throw new Error('Errore invio'); const data = await res.json(); Alert.alert('✅ Creato!', `Post ID: ${data.id}`); setTitolo(''); setCorpo(''); } catch (err) { Alert.alert('❌ Errore', (err as Error).message); } finally { setSalvataggio(false); }};3. Error Handling robusto
Section titled “3. Error Handling robusto”const fetchSicura = async (url: string, options?: RequestInit) => { try { const res = await fetch(url, options); if (!res.ok) throw new Error(`Errore server: ${res.status}`); return { success: true, data: await res.json() }; } catch (err) { const msg = (err as Error).message; if (msg.includes('Network request failed')) { return { success: false, error: 'Nessuna connessione internet' }; } return { success: false, error: msg }; }};
// Usoconst result = await fetchSicura(url);if (result.success) { setDati(result.data);} else { Alert.alert('Errore', result.error);}4. WebSocket
Section titled “4. WebSocket”const ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = () => { console.log('Connesso!'); ws.send('Ciao server!');};
ws.onmessage = (e) => { console.log('Ricevuto:', e.data);};
ws.onerror = (e) => { console.error('Errore WebSocket:', e.message);};
ws.onclose = (e) => { console.log('Connessione chiusa:', e.code, e.reason);};
// Chiuderews.close();5. Tabella riassuntiva
Section titled “5. Tabella riassuntiva”| Operazione | Codice |
|---|---|
| POST | fetch(url, {method:'POST', body: JSON.stringify(d)}) |
| Headers | headers: { 'Content-Type': 'application/json' } |
| Error handling | if (!res.ok) throw Error() |
| WebSocket | new WebSocket(url) |
| WS messaggi | ws.onmessage = (e) => {} |
6. Esercizio
Section titled “6. Esercizio”🎯 “App citazioni”
Section titled “🎯 “App citazioni””Crea un’app che:
- Carica citazione da
https://api.quotable.io/random - Mostra testo + autore
- Bottone “Nuova citazione” → ricarica
- Gestione errori
- ActivityIndicator durante caricamento