RTK Query : Powerful Data fetching

Redux Toolkit is another way to fetch data in React JS application. It is much more easier to fetch data and if something goes wrong , it will enable isError flag for us. And when data fetching is in progress, it will enable isLoading flag for us.

No alt text provided for this image
userApi.js

In side code snippet , createApi is imported form @reduxjs/toolkit/query/react which will gives use predefined hooks like useFetchUsersQuery , useAddUserMutation and useRemoveMutation .

query is for read operation and mutation is for write/update options

createApi takes object with three property

  1. reducerPath
  2. baseQuery
  3. endpoints

reducerPath :

Property on the big state object where all of the API state should be maintained


baseQuery : It is takes your baseUrl for data fetching . But baseUrl provided as object to fetchBaseQuery which is imported from @reduxjs/toolkit/query/react.

endpoints: With the help of this we can define our grouped api like fetchUsers , addUser and removeUser. endpoints can be of two types query and mutation. fetchUser is read operation , so it will be query. We can define this endpoints are query like fetchUsers: builder.query({}). Similarly addUser and removeUser are write operation , so they are mutation. we can write like this addUser: builder.mutation({}) and removeUser: builder.mutation({}) . all mentioned endpoints accept one arguments as object with 'query' as property.

That query function is what we want do with endpoints. like in fetchUsers endpoints , we want to fetch or get list of user , so we defining query function with GET method and url .

How we can use automatically generated hooks by RTK query in Component to fetch data ?

No alt text provided for this image
userList.js

As shown in image, useFetchUserQuery is automatically generated hooks for RTK query when we define endpoints as fetchUsers. We can directly use that hook into our component . useFetchUsersQuery return some important things like data , isError and isLoading. data is returned when api is fulfilled . Initial data is undefined. When data fetching is in-progress isLoading flag set to true. once data fetching is successful , isLoading set to false. If something goes wrong with data fetching , isError flag is set to true.

Whats the store config for RTK query ?

No alt text provided for this image
store/index.js

As shown in the image, userApi gives us reducer ( a combined reducer ) which we will passing to configureStore with reducer as property.

also userApi gives us middleware , which we concatenate with default middleware.




Conclusion : RTK Query can be best option for data fetching when we have standard rest api.

To view or add a comment, sign in

Others also viewed

Explore content categories