Search code examples
reactjstypescriptaxiosreact-typescriptreact-query

Type missinng in React Typescript Axios Response


I'm trying to write an API service in a React app, using Axios and Typescript.

Below is my code:

Interface for Helper API Class

import { AxiosResponse } from 'axios'

export interface PlatformResponse {
    platform: {
        id: string
        image: string
        name: string
    }[]
}

export interface Platform {
    getPlatformResponse: () => Promise<AxiosResponse<PlatformResponse>>
}

My Platform Class

import { AxiosResponse } from 'axios'

class Platforms implements Platform {
    async getPlatformResponse(): Promise<AxiosResponse<PlatformResponse>> {
        const path = 'http://localhost:8080/api/platforms'
        const method = 'get'
        const result = await httpRequest({ path, method })
        return result
    }
}

const PlatformsAPI = new Platforms()
export default PlatformsAPI 

I'm using the react-query library for fetching data, and the code below

const useGetPlatforms = () => {
    console.log('sdfd')
    return useQuery('platform', PlatformsAPI.getPlatformResponse)
}

export default useGetPlatforms

And the Code for my component as below

import { useGetVehicleBrands } from '../../../hooks/RQHooks'

function VehicleBrands() {
    const { data, isLoading } = useGetVehicleBrands()
    console.log('data', data.platform)

    return (
        <>
            <div>
                {data.platform.map((item) =><h1>{item}</h1>)}
            </div>
        </>
    )
}

export default PlatformComponent

The error I'm getting in my above code is that I couldn't access the platform property from the data. Typescript throwing error saying that the platform property not found. Only the property from the AxiosResponse is shown. How to accomplish that the typescript know that data is the type of PlatformResponse. Kindly help to accomplish it.

enter image description here


Solution

  • you get a data property from react-query that contains the unwrapped promise from whatever your queryFn returns.

    an AxiosResponse contains what you're seeing in your screenshot - data, headers, statusText etc.

    Your actual data is inside the data property, so you'd need:

    data.data.platform
    

    The first data being the one from react-query, the second one being the one from axios.

    If you don't need to store request meta-data like headers in your queryCache, it is best to unwrap it inside the queryFn:

    useQuery(
      'platform',
       () => PlatformsAPI.getPlatformResponse().then(response => response.data))
    )
    

    you can also do that inside your PlatformsAPI if you want.