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:
- First, install and import the necessary libraries:
bashnpm install axios react-query
- Set up the request function:
javascriptimport axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://api.example.com' }); const fetchData = async (url) => { const { data } = await axiosInstance.get(url); return data; };
- Use React Query and the custom fetchData function in a React component:
javascriptimport { 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.