DEV Community

Discussion on: Improving API Documentation using React Query and TypeScript

Collapse
phryneas profile image
Lenz Weber • Edited on

To be fair, the above does describe a valid way of doing this with Redux - but the official Redux Toolkit also contains "RTK Query", which does essentially the same as React Query. In RTK Query, a similar functionality would look like

// Need to use the React-specific entry point to import createApi
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { Pokemon } from './types'

// Define a service using a base URL and expected endpoints
export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonById: builder.query<Pokemon, string>({
      query: (id) => `pokemon/${id}`,
    }),
    getAllPokemon:  builder.query<Record<string,Pokemon>, void>({
      query: (id) => `pokemons/all`,
    }),
  }),
})

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPokemonByIdQuery, useGetAllPokemonQuery } = pokemonApi
Enter fullscreen mode Exit fullscreen mode

And this either integrates in your Redux store or you don't set a Redux store up, but just wrap your app into a <ApiProvider api={pokemonApi}> which will automatically set up a Redux store for you.

If you're interested in more, check out redux-toolkit.js.org/tutorials/rtk...

If you want to play around with it, here is a CodeSandbox: codesandbox.io/s/github/reduxjs/re...

Collapse
arn4v profile image
Arnav Gosain Author

I haven't had a chance to try RTK Query, will try it out!

Not mentioning RTK Query is an oversight on my end, I have edited the post to mention it now.