Привет! Решил в общем написать авторизацию бек уже готов а с фронтом мучаюсь, хотел создать хук useProfile чтобы мог доставать все что мне нужно но useQuery меня пиздит и хз за что. А как решить эту проблему я не знаю т.к. даже stackoverflow не помог. Фронт на Next.js 14. Проблема: [{ "resource": "/D:/AniMi/animi-next/hooks/useProfile.ts", "owner": "typescript", "code": "2769", "severity": 8, "message": "No overload matches this call.\n Overload 1 of 3, '(options: UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.\n Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.\n Overload 2 of 3, '(options: DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): DefinedUseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.\n Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.\n Overload 3 of 3, '(options: UseQueryOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.", "source": "ts", "startLineNumber": 5, "startColumn": 29, "endLineNumber": 5, "endColumn": 42 }] Код [{ "resource": "/D:/AniMi/animi-next/hooks/useProfile.ts", "owner": "typescript", "code": "2769", "severity": 8, "message": "No overload matches this call.\n Overload 1 of 3, '(options: UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'UndefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.\n Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.\n Overload 2 of 3, '(options: DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): DefinedUseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'DefinedInitialDataOptions<unknown, Error, unknown, QueryKey>'.\n Type 'string' is not assignable to type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.\n Overload 3 of 3, '(options: UseQueryOptions<unknown, Error, unknown, QueryKey>, queryClient?: QueryClient | undefined): UseQueryResult<unknown, Error>', gave the following error.\n Argument of type 'string' is not assignable to parameter of type 'UseQueryOptions<unknown, Error, unknown, QueryKey>'.", "source": "ts", "startLineNumber": 5, "startColumn": 29, "endLineNumber": 5, "endColumn": 42 }] хук useProfile.ts: import { useQuery } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const { data } = useQuery('get profile', () => UserService.getProfile()); return { profile: data }; }; JS import { useQuery } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const { data } = useQuery('get profile', () => UserService.getProfile()); return { profile: data }; }; Если потребуется вот ещё: user.service.ts: import { instance } from '@/api/api.interceptor'; import { IUser } from '@/types/user.interface'; const USERS = 'users'; type TypeData = { username: string; email: string; avatar: string; banner: string; }; export const UserService = { async getProfile() { return instance<IUser[]>({ url: `/${USERS}/@me`, method: 'GET', }); }, async updateProfile(data: TypeData) { return instance<IUser[]>({ url: `/${USERS}/@me`, method: 'PUT', data, }); }, }; JS import { instance } from '@/api/api.interceptor'; import { IUser } from '@/types/user.interface'; const USERS = 'users'; type TypeData = { username: string; email: string; avatar: string; banner: string; }; export const UserService = { async getProfile() { return instance<IUser[]>({ url: `/${USERS}/@me`, method: 'GET', }); }, async updateProfile(data: TypeData) { return instance<IUser[]>({ url: `/${USERS}/@me`, method: 'PUT', data, }); }, }; api.inteceptor.ts: import { siteAPI } from '@/constants/app.constants'; import axios from 'axios'; import { errorCatch, getContentType } from './api.helper'; import { getAccessToken, removeFromStorage } from '@/services/auth/auth.helper'; import { AuthService } from '@/services/auth/auth.service'; const axiosOptions = { baseURL: siteAPI, headers: getContentType(), }; export const axiosClassic = axios.create(axiosOptions); export const instance = axios.create(axiosOptions); instance.interceptors.request.use(async (config) => { const accessToken = getAccessToken(); if (config.headers && accessToken) { config.headers.Authorization = `Bearer ${accessToken}`; } return config; }); instance.interceptors.request.use( (config) => config, async (error) => { const originalRequest = error.config; if ( (error?.response?.status == 401 || errorCatch(error) === 'jwt expired' || errorCatch(error) === 'jtw muts be provided') && error.config && !error.config._isRetry ) { originalRequest._isRetry = true; try { await AuthService.getNewTokens(); return instance.request(originalRequest); } catch (error) { if (errorCatch(error) === 'jwt expired') { removeFromStorage(); } } } throw error; }, ); JS import { siteAPI } from '@/constants/app.constants'; import axios from 'axios'; import { errorCatch, getContentType } from './api.helper'; import { getAccessToken, removeFromStorage } from '@/services/auth/auth.helper'; import { AuthService } from '@/services/auth/auth.service'; const axiosOptions = { baseURL: siteAPI, headers: getContentType(), }; export const axiosClassic = axios.create(axiosOptions); export const instance = axios.create(axiosOptions); instance.interceptors.request.use(async (config) => { const accessToken = getAccessToken(); if (config.headers && accessToken) { config.headers.Authorization = `Bearer ${accessToken}`; } return config; }); instance.interceptors.request.use( (config) => config, async (error) => { const originalRequest = error.config; if ( (error?.response?.status == 401 || errorCatch(error) === 'jwt expired' || errorCatch(error) === 'jtw muts be provided') && error.config && !error.config._isRetry ) { originalRequest._isRetry = true; try { await AuthService.getNewTokens(); return instance.request(originalRequest); } catch (error) { if (errorCatch(error) === 'jwt expired') { removeFromStorage(); } } } throw error; }, ); user.interface.ts: export interface IUser { _id: string; username: string; email: string; verified: string; avatar: string; banner: string; createdAt: Date; updatedAt: Date; } JS export interface IUser { _id: string; username: string; email: string; verified: string; avatar: string; banner: string; createdAt: Date; updatedAt: Date; } p.s. vuchaev2015 памаги
Риктик Привет! Я вижу, что у тебя возникла проблема с использованием хука `useQuery` в файле `useProfile.ts`. Ошибка говорит о том, что аргумент, который ты передаешь в `useQuery`, имеет тип `string`, в то время как ожидается тип `UseQueryOptions<unknown, Error, unknown, QueryKey>`. Чтобы решить эту проблему, тебе нужно правильно настроить параметры `useQuery`. В данном случае, ты должен передать объект с опциями запроса вместо строки. Вот как это можно сделать: import { useQuery, UseQueryOptions } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const options: UseQueryOptions<unknown, Error, unknown, QueryKey> = { queryKey: 'get profile', queryFn: () => UserService.getProfile(), }; const { data } = useQuery(options); return { profile: data }; }; TYPESCRIPT import { useQuery, UseQueryOptions } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const options: UseQueryOptions<unknown, Error, unknown, QueryKey> = { queryKey: 'get profile', queryFn: () => UserService.getProfile(), }; const { data } = useQuery(options); return { profile: data }; }; Теперь `options` содержит два свойства: `queryKey`, которое задает ключ запроса, и `queryFn`, которое задает функцию для выполнения запроса. Передавай этот объект `options` в `useQuery` и ошибка должна исчезнуть. Попробуй внести эти изменения и проверь, решается ли проблема. Если у тебя возникнут еще вопросы, не стесняйся задавать.
Риктик Я извиняюсь за предыдущую путаницу. Попробуй внести следующие изменения в файл `useProfile.ts`: import { useQuery, UseQueryOptions } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const options: UseQueryOptions<any, Error> = { queryKey: 'get profile', queryFn: () => UserService.getProfile(), }; const { data } = useQuery<any, Error>(options); return { profile: data }; }; TYPESCRIPT import { useQuery, UseQueryOptions } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const options: UseQueryOptions<any, Error> = { queryKey: 'get profile', queryFn: () => UserService.getProfile(), }; const { data } = useQuery<any, Error>(options); return { profile: data }; }; В этом случае, я использовал `any` в качестве типов данных для `UseQueryOptions` и `useQuery`. Попробуй обновить код с этими изменениями и проверь, решается ли проблема. Если ошибка все еще остается, дай мне знать, и мы попробуем найти другое решение.
Риктик Понимаю, что проблема остается. Давай попробуем еще один вариант. Вместо использования `UseQueryOptions` и `useQuery`, попробуй использовать `useQuery` напрямую с передачей ключа запроса и функции запроса: import { useQuery } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const { data } = useQuery('get profile', UserService.getProfile); return { profile: data }; }; TYPESCRIPT import { useQuery } from '@tanstack/react-query'; import { UserService } from '@/services/user.service'; export const useProfile = () => { const { data } = useQuery('get profile', UserService.getProfile); return { profile: data }; }; В этом случае, мы передаем строку `'get profile'` в качестве ключа запроса и функцию `UserService.getProfile` в качестве функции запроса. Попробуй обновить код с этими изменениями и проверь, решается ли проблема. Если ошибка все еще остается, дай мне знать, и мы попробуем найти другое решение.
дело может и не в этом , но в последних версиях React Query ключи для useQuery передаются массивом ['key', ...]