search
HomeWeb Front-endJS TutorialReact CRUD Operations with Axios and React Query

React CRUD Operations with Axios and React Query

In the previous article, Simplifying HTTP Requests in React with Custom Hooks ?, we explored how to simplify HTTP requests using custom hooks. While effective for smaller applications, this approach may become harder to maintain as your React app scales. In this article, we'll dive into how to handle CRUD (Create, Read, Update, Delete) operations in a scalable way using Axios and React Query.

Why Axios and React Query?

  • Axios: A promise-based HTTP client for the browser and Node.js, Axios simplifies sending asynchronous HTTP requests to REST endpoints with clean, readable code.

  • React Query: A powerful data-fetching library that enhances data synchronization, caching, and state management in React. React Query automates data fetching while providing better control over loading and error states.

Setting Up Axios and React Query

First, install the necessary packages:

npm install axios react-query react-router-dom

Setting Up React Query in Your App

Next, configure React Query in your entry file (App.tsx) to manage your application's global query settings.

// src/App.tsx
import { QueryClient, QueryClientProvider } from 'react-query';
import { CustomRouter } from './Router';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,  // Prevent refetch on tab/window switch
      retry: 1,                     // Retry failed queries once
    },
  },
});

const App: React.FC = () => (
  <queryclientprovider client="{queryClient}">
    <customrouter></customrouter>
  </queryclientprovider>
);

export default App;

Setting Up Axios with Interceptors

To handle authentication globally, we can create an Axios instance and use interceptors to attach the Authorization header for authenticated requests.

// src/config/axiosApi.ts
import axios from 'axios';

const authenticatedApi = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,  // Environment-specific base URL
  headers: {
    'Content-Type': 'application/json',
  },
});

// Attach Authorization token to requests if present
authenticatedApi.interceptors.request.use((config) => {
  const token = localStorage.getItem('crud-app-auth-token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export { authenticatedApi };

Creating API Functions for CRUD Operations

Let's define functions that interact with our API to perform CRUD operations using Axios:

// src/data/api/post.ts
import { authenticatedApi } from '../../config/axiosApi';

// Error handler function to standardize error messages
export const handleApiError = (error: any): never => {
  if (error.message === 'Network Error') {
    throw new Error('Network Error. Please try again later.');
  } else if (error.response?.data?.error) {
    throw new Error(error.response.data.error);
  } else if (error.response) {
    throw new Error('A server error occurred.');
  } else {
    throw new Error(error.message || 'An unknown error occurred.');
  }
};

// General function to handle API requests
export const apiCall = async <t>(
  method: 'get' | 'post' | 'put' | 'delete',
  url: string,
  data?: any,
): Promise<t> => {
  try {
    const response = await authenticatedApi[method](url, data);
    return response.data;
  } catch (error) {
    throw handleApiError(error);
  }
};

// CRUD functions for the post feed
export const createPostApi = (post: any) => apiCall<any>('post', 'posts', post);
export const getPostsApi = () => apiCall<any>('get', 'posts');
export const updatePostApi = (id: string, post: any) => apiCall<any>('put', `posts/${id}`, post);
export const deletePostApi = (id: string) => apiCall<any>('delete', `posts/${id}`);
</any></any></any></any></t></t>

Using React Query Hooks for CRUD Operations

Now that we have API functions, we can use React Query to handle state management and data fetching for these operations.

// src/data/hooks/post.ts
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { createPostApi, getPostsApi, updatePostApi, deletePostApi } from '../api/post';

// Custom hooks for CRUD operations
export const useCreatePostApi = () => {
  const queryClient = useQueryClient();
  return useMutation(createPostApi, {
    onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after a new post is created
  });
};

export const useGetPostsApi = () => useQuery(['posts'], getPostsApi);

export const useUpdatePostApi = () => {
  const queryClient = useQueryClient();
  return useMutation(updatePostApi, {
    onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after an update
  });
};

export const useDeletePostApi = () => {
  const queryClient = useQueryClient();
  return useMutation(deletePostApi, {
    onSuccess: () => queryClient.invalidateQueries(['posts']), // Refetch posts after deletion
  });
};

Consuming CRUD Hooks in a Component

Finally, we can build a simple component that consumes the custom hooks and allows users to create, edit, and delete posts.

// src/components/PostCard.tsx
import React, { useState } from 'react';
import { useGetPostsApi, useDeletePostApi, useUpdatePostApi, useCreatePostApi } from '../data/hooks/post';
import { toast } from '../components/Toast';  // Assume a toast component exists

const PostCard: React.FC = () => {
  const { data: posts, isLoading, error } = useGetPostsApi();
  const deletePost = useDeletePostApi();
  const updatePost = useUpdatePostApi();
  const createPost = useCreatePostApi();
  const [newPost, setNewPost] = useState({ title: '', content: '' });

  const handleCreate = async () => {
    try {
      await createPost.mutateAsync(newPost);
      setNewPost({ title: '', content: '' });
      toast.success('Post created successfully');
    } catch (error) {
      toast.error(error.message);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deletePost.mutateAsync(id);
      toast.success('Post deleted successfully');
    } catch (error) {
      toast.error(error.message);
    }
  };

  const handleEdit = async (id: string, updatedPost: any) => {
    try {
      await updatePost.mutateAsync({ id, ...updatedPost });
      toast.success('Post updated successfully');
    } catch (error) {
      toast.error(error.message);
    }
  };

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <div>
        <input type="text" value="{newPost.title}" onchange="{(e)"> setNewPost({ ...newPost, title: e.target.value })}
          placeholder="Title"
        />
        <input type="text" value="{newPost.content}" onchange="{(e)"> setNewPost({ ...newPost, content: e.target.value })}
          placeholder="Content"
        />
        <button onclick="{handleCreate}" disabled>
          {createPost.isLoading ? 'Creating...' : 'Create Post'}
        </button>
      </div>

      {posts?.map((post: any) => (
        <div key="{post.id}">
          <h3 id="post-title">{post.title}</h3>
          <p>{post.content}</p>
          <button onclick="{()"> handleEdit(post.id, { title: 'Updated Title', content: 'Updated Content' })}>
            Edit
          </button>
          <button onclick="{()"> handleDelete(post.id)}>
            Delete
          </button>
        </div>
      ))}
    </div>
  );
};

export default PostCard;

Conclusion

By using Axios and React Query, you can streamline CRUD operations in your React applications. This combination results in clean, maintainable code, improving scalability and performance. Use these tools to simplify state management and data fetching as your app grows.

For more insights on React, TypeScript, and modern web development practices, follow me on Dev.to! ?‍?

The above is the detailed content of React CRUD Operations with Axios and React Query. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software