React6 min read

React API Integration

Fetch data from APIs and handle loading and error states.

Sarah Johnson
December 20, 2025
0.0k0

Learn to fetch data from APIs in React.

Using Fetch

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/users')
      .then(res => res.json())
      .then(data => {
        setUsers(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      {users.map(user => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

POST Request

const createUser = async (userData) => {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData)
  });
  return response.json();
};

With Axios

npm install axios
import axios from 'axios';

useEffect(() => {
  axios.get('https://api.example.com/users')
    .then(res => setUsers(res.data))
    .catch(err => setError(err.message));
}, []);

Remember

  • Handle loading states
  • Handle errors
  • Clean up with AbortController
  • Use try-catch with async/await

Next: Learn form validation!

#React#API#Fetch#Axios#Intermediate