DEV Community

Cover image for How to setup Redux tool kit for RTK query
Ifeanyi Chima
Ifeanyi Chima

Posted on • Edited on

How to setup Redux tool kit for RTK query

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.

Image description

  1. Run create-react-app
    npx create-react-app .

  2. Install the following dependecies.




npm install react-redux @reduxjs/toolkit 



Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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>
);



Enter fullscreen mode Exit fullscreen mode

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 => ({})
})



Enter fullscreen mode Exit fullscreen mode

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
})



Enter fullscreen mode Exit fullscreen mode

Thank You, Please follow me

twitter
github
linkedin

Top comments (0)