1.
Fetching Data with Fetch API and Axios
1.1 Fetch API
The Fetch API is built into modern JavaScript environments and is used to make HTTP requests to
fetch resources over the network.
Basic Syntax:
javascript
fetch('https://api.example.com/data')
.then(response => response.json()) // Parse the JSON from the response
.then(data => console.log(data)) // Handle the data
.catch(error => console.error(error)); // Handle errors
Asynchronous with async/await:
javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
fetchData();
1.2 Axios
Axios is a popular third-party library that simplifies making HTTP requests, providing a cleaner API
than Fetch. It also offers additional features like automatic JSON parsing and request cancellation.
Basic Syntax:
javascript
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Using async/await with Axios:
javascript
Copy code
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
fetchData();
Axios Configuration: Axios provides more control over requests, such as setting headers,
timeout, and base URL.
javascript
Copy code
axios.get('https://api.example.com/data', {
headers: { Authorization: 'Bearer your-token' },
timeout: 5000, // Timeout after 5 seconds
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
2. Working with RESTful APIs
A RESTful API is an architectural style that uses HTTP methods (GET, POST, PUT, DELETE) to interact
with resources represented in a standardized format, typically JSON.
GET Request: Retrieve data from the server
POST Request: Send data to the server (often for creating a resource)
PUT/PATCH Request: Update existing data
DELETE Request: Delete data
Example of a typical RESTful API interaction using Axios:
javascript
Copy code
// GET: Fetch data
axios.get('/users')
.then(response => console.log(response.data));
// POST: Send new data
axios.post('/users', { name: 'John Doe' })
.then(response => console.log(response.data));
// PUT: Update data
axios.put('/users/1', { name: 'Jane Doe' })
.then(response => console.log(response.data));
// DELETE: Remove data
axios.delete('/users/1')
.then(response => console.log(response.data));
3. Error Handling and Loading States
3.1 Error Handling
When working with APIs, handling errors gracefully is critical for a good user experience.
Common Errors to Handle:
o Network Errors
o Response errors (e.g., 4xx, 5xx HTTP errors)
o Timeout Errors
Example of error handling in Fetch and Axios:
javascript
Copy code
// Fetch API Error Handling
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
// Axios Error Handling
axios.get('/data')
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
// Server responded with a status other than 200
console.error('Server Error:', error.response.status);
} else if (error.request) {
// No response was received
console.error('Network Error:', error.request);
} else {
console.error('Error:', error.message);
});
3.2 Loading States
A loading state informs users that data is being fetched, improving user experience.
Example using React State:
javascript
Copy code
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
console.error('Error fetching data:', error);
setLoading(false);
});
}, []);
if (loading) {
return <div>Loading...</div>;
return <div>{JSON.stringify(data)}</div>;
4. Using React Query for Data Fetching and Caching
React Query is a library that abstracts and automates common data-fetching tasks, including caching,
background refetching, pagination, and synchronization.
Basic Setup:
First, install React Query:
bash
Copy code
npm install react-query
Then wrap your app in a QueryClientProvider:
javascript
Copy code
import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your components here */}
</QueryClientProvider>
);
Fetching Data with React Query:
Use useQuery hook to fetch data:
javascript
Copy code
import { useQuery } from 'react-query';
function fetchData() {
return axios.get('https://api.example.com/data');
function DataComponent() {
const { data, error, isLoading } = useQuery('data', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error fetching data</div>;
return <div>{JSON.stringify(data)}</div>;
React Query will automatically handle caching, background fetching, and state management.
5. Introduction to GraphQL and Apollo Client
5.1 GraphQL Overview
GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike
REST, which exposes multiple endpoints, GraphQL typically exposes a single endpoint.
Basic GraphQL Query:
graphql
Copy code
query {
users {
id
name
GraphQL Benefits:
o Single endpoint
o Precise queries (avoid over-fetching or under-fetching data)
o Real-time updates with subscriptions
5.2 Apollo Client
Apollo Client is a popular library used to manage GraphQL data in client-side applications.
Basic Setup with Apollo Client:
Install Apollo Client:
bash
Copy code
npm install @apollo/client graphql
Setup Apollo Client:
javascript
Copy code
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache(),
});
function App() {
return (
<ApolloProvider client={client}>
{/* Your components */}
</ApolloProvider>
);
Fetching Data with Apollo Client:
Using useQuery from Apollo Client:
javascript
Copy code
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query {
users {
id
name
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
6. Authentication and Authorization (OAuth, JWT)
6.1 Authentication and Authorization
Authentication: Verifies the identity of the user (e.g., username/password).
Authorization: Grants or denies access to resources based on the authenticated user’s
permissions.
6.2 OAuth (Open Authorization)
OAuth is a standard for access delegation, allowing third-party services to access a user’s resources
without exposing credentials.
OAuth Flow:
1. User logs into a service.
2. The service provides an authorization code.
3. The client exchanges the authorization code for an access token.
6.3 JWT (JSON Web Tokens)
JWT is a compact, URL-safe means of representing claims between two parties.
JWT Structure:
o Header: Metadata about the token
o Payload: Claims about the user or session