In this article, we review RTK query usage in Meshery codebase. We will look at:
What is Meshery?
What is RTK Query?
RTK Query usage in Meshery.
I study patterns used in an open source project found on Github Trending. For this week, I reviewed some parts of Meshery codebase and wrote this article.
Meshery is the extensible Kubernetes manager. Meshery has 380+ Built-In integrations for your Cloud Native Infrastructure and Apps. Meshery seamlessly integrates with every CNCF project, your existing tools, multiple Clouds and Kubernetes clusters.
RTK Query is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
RTK Query is an optional addon included in the Redux Toolkit package, and its functionality is built on top of the other APIs in Redux Toolkit.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'import type { Pokemon } from './types'// Define a service using a base URL and expected endpointsexport const pokemonApi = createApi({ reducerPath: 'pokemonApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }), endpoints: (build) => ({ getPokemonByName: build.query<Pokemon, string>({ query: (name) => `pokemon/${name}`, }), }),})// Export hooks for usage in functional components, which are// auto-generated based on the defined endpointsexport const { useGetPokemonByNameQuery } = pokemonApi
Configure the store
The “API slice” also contains an auto-generated Redux slice reducer and a custom middleware that manages subscription lifetimes. Both of those need to be added to the Redux store:
import { configureStore } from '@reduxjs/toolkit'// Or from '@reduxjs/toolkit/query/react'import { setupListeners } from '@reduxjs/toolkit/query'import { pokemonApi } from './services/pokemon'export const store = configureStore({ reducer: { // Add the generated reducer as a specific top-level slice [pokemonApi.reducerPath]: pokemonApi.reducer, }, // Adding the api middleware enables caching, invalidation, polling, // and other useful features of `rtk-query`. middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(pokemonApi.middleware),})// optional, but required for refetchOnFocus/refetchOnReconnect behaviors// see `setupListeners` docs - takes an optional callback as the 2nd arg for customizationsetupListeners(store.dispatch)
Use hooks in components
import * as React from 'react'import { useGetPokemonByNameQuery } from './services/pokemon'export default function App() { // Using a query hook automatically fetches data and returns query values const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur') // Individual hooks are also accessible under the generated endpoints: // const { data, error, isLoading } = pokemonApi.endpoints.getPokemonByName.useQuery('bulbasaur') // render UI based on data and loading state}