乐闻世界logo
搜索文章和话题

Is there a way to configure a base url on react- query 's QueryClient?

1个答案

1

When using React Query for data fetching and management, the QueryClient itself does not natively support configuring a base URL. React Query is primarily responsible for data fetching, caching, synchronization, and state management, but it does not handle the specifics of request sending. Therefore, configuring a base URL is typically implemented using request-sending tools or methods, such as Axios or fetch.

However, you can configure the base URL by utilizing a custom function that integrates React Query. This approach helps maintain clean and consistent code, and allows you to reuse the request function with the base URL across the entire project. Below is an example of implementing a request function with a base URL using Axios and React Query:

  1. First, install and import the necessary libraries:
bash
npm install axios react-query
  1. Set up the request function:
javascript
import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://api.example.com' }); const fetchData = async (url) => { const { data } = await axiosInstance.get(url); return data; };
  1. Use React Query and the custom fetchData function in a React component:
javascript
import { useQuery } from 'react-query'; function MyComponent() { const { data, error, isLoading } = useQuery('data', () => fetchData('/endpoint')); if (isLoading) return <div>Loading...</div>; if (error) return <div>An error occurred: {error.message}</div>; return ( <div> {/* render your data here */} {data.map(item => ( <div key={item.id}>{item.title}</div> ))} </div> ); }

By doing this, you can centralize the management of the API's base URL and integrate it with React Query's caching and state management features, effectively improving application performance and user experience.

2024年6月29日 12:07 回复

你的答案