Home > Mobile >  Types error with AxiosResponse and UseQueryResult
Types error with AxiosResponse and UseQueryResult

Time:01-24

I am using react query in my typescript project.

export type CarouselData = {
  name: string;
  body: string;
  imgOne: string;
  imgTwo: string;
};

export const getCarouselData = async (): Promise<
  AxiosResponse<CarouselData[]>
> => {
  return await (
    await publicAPI.get('/carouselData')
  );
};

export const useGetCarouselData = (): UseQueryResult<
  Promise<AxiosResponse<CarouselData[]>>
> => {
  return useQuery('getCarouselData', getCarouselData);
};

In my component, I am consuming this as follows.

type Item = {
    name: string,
    body: string,
    imgOne: string,
    imgTwo: string,
}

export const HomeCarousel: FC = () => {
    const {Root} = useStyles();

    const result = useGetCarouselData();
    
    console.log(result.data.data); //data.data is giving an error
    return (
        <Root>
            <Carousel<Item[]>>
                {result.data.data.map((item, index)=> {
                    return <CarouselItem key={index} name={item.name} body={item.body} imgOne={item.imgOne} imgTwo={item.imgTwo}/>
                })}
            </Carousel>
        </Root>
    )
}

Now, I am getting an error Property 'data' does not exist on type 'Promise<AxiosResponse<CarouselData[], any>>'.ts(2339) that shouldn't be there?

I want to know why this is happening or how to resolve this. : )

Any help is appreciated.

CodePudding user response:

react-query unwraps the Promise, so you'd want: UseQueryResult<AxiosResponse<CarouselData[]>>

Or, you can just use type inference. Leave out the type and let the compiler figure it out :)

  •  Tags:  
  • Related