Search code examples
react-nativereact-reduxreact-hooksexportk-query

How to log and display partial data with RTK query?


I'm creating an mobile App with react native typescript and expo with help of rtk-query. I'm trying to get partial data from API https://pokeapi.co/api/v2/pokemon/snorlax/. For example from API I'm only trying to get name or something else whatever but some partial data.

usersApi.tsx

// Need to use the React-specific entry point to allow generating React hooks
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

// Define a service using a base URL and expected endpoints
export const pokemonApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://pokeapi.co/api/v2/',
    method: 'GET'
   }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query({
      query: (name: string) => `pokemon/${name}`,
    }),
  }),
})

export const { useGetPokemonByNameQuery } = pokemonApi

ContactScreen.tsx

import React from 'react';
import {
  Image,
  ImageBackground,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';

import { View, Text } from '@components/Themed';
import { useFonts } from '@use-expo/font';
import * as Linking from 'expo-linking';
import AppLoading from 'expo-app-loading';
import { useGetPokemonByNameQuery } from '../apiCalls/usersApi';

const ContactScreen = ({name}: {name: string}) => {
  const [isLoaded] = useFonts({
    'Poppins-Medium': require('../../assets/fonts/Poppins-Medium.otf'),
    'Poppins-Regular': require('../../assets/fonts/Poppins-Regular.otf')
  });

  const { data } = useGetPokemonByNameQuery(name)
  
  console.log(data)

[...]

App.tsx

[...]

export default function App() {
  const isLoadingComplete = useCachedResources();
  const colorScheme = useColorScheme();

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      <Provider store={store}>
        <SafeAreaProvider>
          <I18n />
          <ContactScreen name={'snorlax'}/>
          <StatusBar />
        </SafeAreaProvider>
      </Provider>
    );
  }
}

From ContactScreen.tsx I'm getting fetched data but a lot of crap which I don't need. Something like console.log(data.species.name) doesn't work and getting me an error TypeError data is undefinedWHICH onlyconsole.log(data)` doesn't.


Solution

  • You are probably accessing data properties without checking if data is fetched yet.

    if (data && data.species) {
      console.log(data.species.name)
    }
    

    or

    console.log(data?.species?.name)