Usando Fetch
📝 GET Request
💡 Buscar Dados
fetch('https://api.exemplo.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Erro na requisição');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
📝 POST Request
💡 Criar Dados
fetch('https://api.exemplo.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: 'João',
email: 'joao@exemplo.com'
})
})
.then(response => response.json())
.then(data => console.log(data));
📝 Com Async/Await
💡 Sintaxe Moderna
async function buscarUsuarios() {
try {
const response = await fetch('https://api.exemplo.com/users');
if (!response.ok) {
throw new Error('Erro na requisição');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
⚛️ Em React com useEffect
💡 Componente React
import { useState, useEffect } from 'react';
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://api.exemplo.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<div>
{users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}