Redux toolkit query or RTK query for short is the greatest human invention since the wheel. It simplifies performing asynchronous tasks such as fetching data from an API. In this article, I will show you how to set up your project to use RTK query.
Run create-react-app
npx create-react-app .
Install the following dependecies.
npm install react-redux @reduxjs/toolkit
Attention
please note, all files for a single feature should be in the same folder, meaning everything concerning posts should be in a folder called posts
setup a store
// src/app/store.js
import { configureStore } from "@reduxjs/toolkit"
import { apiSlice } from "./api/apiSlice";
export const store = configureStore({
reducer: {
// reducer for slice goes here
},
})
export default store
Provide the store to the App
wrap the entire app with the store.
// index.js
import App from './App';
import { store } from './app/store'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
create an API slice
// src/app/api/apiSlice.js
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
const baseQuery = fetchBaseQuery({
baseUrl: "https://ifeanyi-stock-backend.herokuapp.com/"
})
export const apiSlice = createApi({
baseQuery: baseQuery,
endpoints: builder => ({})
})
Add the API Slice reducer to the store.
apiSlice.reducerPath
helps us to dynamically assign a name to the API slice reducer.
import { configureStore } from "@reduxjs/toolkit"
import { apiSlice } from "./api/apiSlice";
export const store = configureStore({
reducer: {
[apiSlice.reducerPath]: apiSlice.reducer
},
middleware: getDefaultMiddleware => getDefaultMiddleware().concat(apiSlice.middleware),
devTools: true
})
Thank You, Please follow me
Top comments (0)