React Query and Axios setting

orangesky·2023년 12월 15일

Study

목록 보기
2/9

To set up React Query in your React project and use it to send a GET request using Axios, follow these steps:

1. Install React Query and Axios:

If you haven't already installed React Query and Axios, add them to your project using npm:

npm install react-query axios

2. Create a QueryClient Instance:

Import QueryClient and QueryClientProvider from React Query and create a QueryClient instance. This will manage the queries and cache of your application.

import { QueryClient, QueryClientProvider } from 'react-query';

const queryClient = new QueryClient();

3. Wrap Your Application with QueryClientProvider:

Use QueryClientProvider to provide the queryClient instance to your application. This is typically done at the root of your application.


// In your main file like index.js or App.js
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

4. Creating a Fetch Function using Axios:

Define a function that uses Axios to fetch data from your API.

import axios from 'axios';

const fetchMyData = async () => {
  const { data } = await axios.get('https://your-api-url.com/data');
  return data;
};

4. Using useQuery to Fetch Data:

In your component, use the useQuery hook from React Query to fetch data using the function you created.

import { useQuery } from 'react-query';

function MyComponent() {
  const { data, isLoading, error } = useQuery('myData', fetchMyData);

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

  return (
    <div>
      {/* Render your data here */}
    </div>
  );
}

OR

const response = useQuery({
    queryKey: ['images'],
    queryFn: async () => {
        const result = await axios.get(url);
        return result.data;
    },
});
profile
Dev in Progress

0개의 댓글