Create a new API slice using createApi from @reduxjs/toolkit/query:
jsx
// api.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/api' }), // specify the base URL of your backend API
endpoints: (builder) => ({
// define your endpoints here
getUsers: builder.query({
query: () => 'users', // specify the relative URL for fetching users
}),
}),
});
export const { useGetUsersQuery } = api;
Create a Redux store and add the api.reducerPath to the reducer:
jsx
// store.js
import { configureStore } from '@reduxjs/toolkit';
import { api } from './api';
export const store = configureStore({
reducer: {
[api.reducerPath]: api.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(api.middleware),
});
Wrap your app with the Provider component from react-redux and include the api and store:
jsx
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Use the generated useGetUsersQuery hook to fetch data in your component:
jsx
// App.js
import React, { useEffect } from 'react';
import { useGetUsersQuery } from './api';
const App = () => {
const { data, error, isLoading } = useGetUsersQuery();
useEffect(() => {
// Fetch users when the component mounts
// You can also trigger the request manually using a button or other event
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Users</h1>
<ul>
{data && data.map((user) => <li key={user.id}>{user.name}</li>)}
</ul>
</div>
);
};
export default App;
That's it! Now, when the App component renders, it will automatically fetch the users' data from the backend using the useGetUsersQuery hook provided by RTK Query. The fetched data will be available in the data property, and any error or loading state will be handled as well.