TanStackT
TanStack2y ago
16 replies
technological-jade

useQuery - select return undefined data

Hello guys,
I have a custom hooks who goes like this:

import { useQuery } from "@tanstack/react-query"

import axios from "@/config/axios"
import { Chat, IGiftedChat } from "../utils/types"

const useGetChat = (id: string) => {
    const query = useQuery({
        queryKey: ["chat", id],
        queryFn: async () => {
            const response = await axios.get<Chat>(`/chats/${id}`)
            return response.data
        },
        select: (data): IGiftedChat => {
            return {
                id: data.id,
                user: data.contact,
                messages: data.messages.map((message) => ({
                    _id: data.id,
                    text: message.content,
                    createdAt: new Date(message.updatedAt),
                    user: {
                        _id: data.contact.id,
                        name: data.contact.firstname,
                        avatar: data.contact.avatar ?? undefined,
                    },
                })),
            }
        },
    })

    return query
}

export default useGetChat


when I try to use it like that:
const { data, isLoading } = useGetChat(params?.id as string)

I have undefined as the result below the result when I'm logging: data and error

undefined [TypeError: Cannot read property 'map' of undefined]

Can someone help me?
Was this page helpful?