Reputation: 3
I'm using next.js with RTK query. I created api, configured endpoints with queryFn
instead of query
and got an error:
Error
How I can fix this error?
ContentStore.ts
export const contentApi = createApi({
reducerPath: 'api/content',
baseQuery: fetchBaseQuery({
baseUrl: ''
}),
endpoints: (build) => ({
getNewMovies: build.query<any, ContentApi.GetNewMoviesRequestParams>({
queryFn: (params: ContentApi.GetNewMoviesRequestParams) => ContentApiClient.getNewMovies(params),
})
})
})
ContentApiClient.ts
class ContentApiClientClass extends ApiClientClass {
baseUrl = ContentApiClientConstants.baseUrl
async getNewMovies(params?: ContentApi.GetNewMoviesRequestParams) {
return await this.getRequest({
url: 'https://jsonplaceholder.typicode.com/posts',
params
})
}
}
export const ContentApiClient = new ContentApiClientClass()
ApiClient.class.ts
class ApiClientClass {
axiosInstance: AxiosInstance
constructor(config?: AxiosRequestConfig) {
this.axiosInstance = this.createInstance(config)
}
private createInstance(config?: AxiosRequestConfig) {
return axios.create({
...config,
timeout: 60000,
headers: {
'Cache-control': 'no-cache',
...(config?.headers || {})
}
})
}
private async axiosRequest<R>(context: AxiosRequestConfig): Promise<AxiosResponse<R>> {
try {
return await this.axiosInstance(context)
} catch (error) {
if (axios.isCancel(error)) {
throw new Error(`Request has aborted. Url: ${context.url}`)
}
throw error
}
}
async getRequest<R>(context: AxiosRequestConfig): Promise<AxiosResponse<R>> {
return await this.axiosRequest({
...context,
method: 'get'
})
}
}
export default ApiClientClass
Upvotes: 0
Views: 2253
Reputation: 44078
A queryFn
has to return an object in either the shape { data: something }
or { error: something }
. It should not throw
anything.
That said, you are doing a lot of stuff here just to do an api request. While it is certainly possible to go to that length, I'd really recommend you to just use baseQuery
with the query
function. baseFetchQuery
should do everything you need, but if you're hell-bent on adding another 6kb of bundle size for axios, the documentation also has examples on how to write an axios baseQuery.
Upvotes: 2