[go: up one dir, main page]

0% found this document useful (0 votes)
17 views7 pages

React Beyond Basics & Backend

The document provides examples of React components for fetching posts using Fetch API, Axios, and React Query, highlighting their features and differences. It also introduces RTK Query for CRUD operations integrated with Redux, showcasing its advantages over traditional methods. Key comparisons include state management, data caching, and automatic refetching capabilities.

Uploaded by

bhavyamathur2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views7 pages

React Beyond Basics & Backend

The document provides examples of React components for fetching posts using Fetch API, Axios, and React Query, highlighting their features and differences. It also introduces RTK Query for CRUD operations integrated with Redux, showcasing its advantages over traditional methods. Key comparisons include state management, data caching, and automatic refetching capabilities.

Uploaded by

bhavyamathur2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

ASMITA SARKAR

1. React Component: Fetch API Example

import React, { useEffect, useState } from 'react';

function FetchPosts() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then((data) => {
setPosts(data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);

if (loading) return <p>Loading posts...</p>;


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

return (
<ul>
{posts.slice(0, 5).map((post) => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
);
}

2. React Component: Axios Example

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function AxiosPosts() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
setPosts(response.data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);

if (loading) return <p>Loading posts...</p>;


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

return (
<ul>
{posts.slice(0, 5).map((post) => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
);
}

3. Fetch API vs Axios: Feature Comparison

Below is a table comparing the native Fetch API and the Axios library for making HTTP requests in
JavaScript.

Comparison table of native Fetch API vs Axios library features.

4. React Query Example: Advanced Data Fetching

import React from 'react';


import { useQuery } from '@tanstack/react-query';

function ReactQueryPosts() {
const { data, error, isLoading, isError, isFetching } = useQuery({
queryKey: ['posts'],
queryFn: () =>
fetch('https://jsonplaceholder.typicode.com/posts').then(res => {
if (!res.ok) throw new Error('Network response was not ok');
return res.json();
}),
staleTime: 1000 * 60 * 5, // 5 minutes
refetchOnWindowFocus: true,
});

if (isLoading) return <p>Loading posts...</p>;


if (isError) return <p>Error: {error.message}</p>;

return (
<div>
{isFetching && <span>Background updating...</span>}
<ul>
{data.slice(0, 5).map((post) => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}

React Query Features Demonstrated:

• Data caching: Data is cached and reused for fast UI updates.

• Automatic refetching: Data auto-refreshes on window focus or at intervals.

• Background sync: UI can show when background updates are happening.

• Built-in state hooks: Loading, error, and fetching states are handled out-of-the-box.

5. RTK Query Integration: CRUD Operations Example

Setup:

• Install: npm install @reduxjs/toolkit react-redux

• Add RTK Query API slice to your Redux store.

API Slice Example:


// features/api/apiSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const api = createApi({


reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }),
endpoints: (builder) => ({
getPosts: builder.query({ query: () => 'posts' }),
addPost: builder.mutation({ query: (newPost) => ({
url: 'posts',
method: 'POST',
body: newPost,
})}),
updatePost: builder.mutation({ query: ({ id, ...patch }) => ({
url: `posts/${id}`,
method: 'PATCH',
body: patch,
})}),
deletePost: builder.mutation({ query: (id) => ({
url: `posts/${id}`,
method: 'DELETE',
})}),
}),
});

export const {
useGetPostsQuery,
useAddPostMutation,
useUpdatePostMutation,
useDeletePostMutation,
} = api;

Usage in a Component:

import React from 'react';


import { useGetPostsQuery, useAddPostMutation, useUpdatePostMutation,
useDeletePostMutation } from './features/api/apiSlice';

function PostsRTKQuery() {
const { data: posts, error, isLoading } = useGetPostsQuery();
const [addPost] = useAddPostMutation();
const [updatePost] = useUpdatePostMutation();
const [deletePost] = useDeletePostMutation();

// Example CRUD handlers here...

if (isLoading) return <p>Loading posts...</p>;


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

return (
<ul>
{posts.slice(0, 5).map(post => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
{/* Add buttons for update/delete as needed */}
</li>
))}
</ul>
);
}

RTK Query vs Other Methods

Feature Fetch API / Axios React Query RTK Query

State Management Manual (useState/useEffect) External (React Query hooks) Integrated with Redux store

Data Caching No Yes Yes

Automatic Refetching No Yes Yes

Background Sync No Yes Yes

CRUD Operations Manual Manual Built-in endpoints/mutations

DevTools Support No Yes Yes

Integration with Redux Manual No Native

Summary:

• Fetch API/Axios: Good for simple cases, but require manual state and error handling.
• React Query: Excellent for data fetching, caching, and background sync, but not tied to Redux.

• RTK Query: Combines data fetching with Redux, offers easy CRUD, caching, and is ideal for Redux-
based apps.

You might also like