👋 Hello, front-enders!
Today we will analyze one of the most important topics in the world of JavaScript and React — working with the API. We will learn how to send HTTP requests, handle errors, and use popular libraries such as fetch, axios, and TanStack Query.
📡 What is an API?
API (Application Programming Interface) is an interface through which programs exchange data with each other. For example, your React application can receive posts from a remote server via the API.
🛠️ APIs are often created using frameworks:
JavaScript — Express.js
Python — Django / Flask
Go — Gin
Java — Spring Boot
C# — ASP.NET Core
🔄 What is API processing?
API processing is the process of sending HTTP requests to the server and processing the received response. In JavaScript and React, the following are most often used:
fetch— built-in browser methodaxios— a popular external libraryTanStack Query(formerly React Query) — a library for easy management of asynchronous data in React
📬 Basic HTTP methods
Method | Purpose |
|---|---|
| Data collection |
| Sending new data |
| Complete resource update |
| Partial update of the resource |
| Deleting data from the server |
⚙️ Working with the API through fetch
Simple GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => scrib.show(data))
.catch(err => scrib.show('Error:', err));POST request with body
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'JS is cool!',
body: 'Scribbler allows you to combine HTML and JS',
userId: 1
})
})
.then(res => res.json())
.then(data => scrib.show(data))
.catch(err => scrib.show('Error:', err));Error handling via try/catch
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Network error');
const data = await response.json();
scrib.show(data);
} catch (err) {
scrib.show('Error:', err);
} finally {
scrib.show('Request completed');
}
}
getData();⚡ Using axios
axios offers cleaner syntax and convenient error handling.
GET request
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(res => scrib.show(res.data))
.catch(err => scrib.show('Error:', err));POST request
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Axios rules!',
body: 'Error handling is much easier',
userId: 1
}, {
headers: { 'Content-Type': 'application/json' }
})
.then(res => scrib.show(res.data))
.catch(err => scrib.show('Error:', err));Advanced error handling
axios.get('https://jsonpl.typicode.com/posts')
.catch(error => {
if (error.response) {
scrib.show('Server error:', error.response.status);
} else if (error.request) {
scrib.show('No response from the server');
} else {
scrib.show('Request error:', error.message);
}
});⚛️ API in React (useEffect + useState)
import { useEffect, useState } from 'react';
function Posts() {
const [posts, setPosts] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => {
if (!res.ok) throw new Error('Error retrieving data');
return res.json();
})
.then(setPosts)
.catch(err => setError(err.message));
}, []);
if (error) return <p>Ошибка: {error}</p>;
return (
<div>
<h2>Посты</h2>
<ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>
</div>
);
}⚙️ TanStack Query (React Query)
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
};
function Posts() {
const { data: posts, error, isLoading } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts
});
if (isLoading) return <p>Загрузка...</p>;
if (error) return <p>Ошибка: {error.message}</p>;
return <ul>{posts.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}✅ Conclusions
📌 API processing is a key skill in web development. The main thing:
Master
fetchandaxiosUnderstand HTTP methods
Be able to handle errors
Use
useEffectin ReactAutomate data loading with TanStack Query
