I code a reusable Api file like this:
import axios from “axios”;
const axiosInstance= axios.create({
baseURL:“https://jsonplaceholder.typicode.com”
})class APIClient{
endpoint:string
constructor(endpoint:string){
this.endpoint=endpoint
}getAll=()=>{ return axiosInstance.get<T[]>(this.endpoint) .then(res=>res.data) } post=(data:T)=>{
return axiosInstance.post<T>(this.endpoint,data).then(res=>res.data)
}
}
export default APIClient
and after that I use it in ine of my components:
import { useMutation, useQueryClient } from “@tanstack/react-query”;
import { Catch_Key_Todos } from “…/queryClient/constants”;
import APIClient from “…/queryClient/Services/ApiClient”;
import { Todo } from “./useTodo”;const apiClient=new APIClient(“/todos”)
interface AddTodoContext {
previousTodos: Todo;
}
const useAddTodo = (onAdd:()=>void) => {
const queryClient = useQueryClient();return useMutation<Todo, Error, Todo, AddTodoContext>({
mutationFn: apiClient.post, onMutate: (newTodo: Todo) => { const previousTodos=queryClient.getQueryData<Todo[]>(Catch_Key_Todos) || [] queryClient.setQueryData<Todo[]>(Catch_Key_Todos, (todoes=[]) => [ newTodo, ...todoes ]); onAdd()
return {previousTodos}},
onSuccess: (savedTodo, newTodo) => { queryClient.setQueryData<Todo[]>(Catch_Key_Todos, (todos) => todos?.map((todo) => (todo == newTodo ? savedTodo : todo)));}, onError:(error,newTodo,context)=>{
if (!context) return
queryClient.setQueryData<Todo>(Catch_Key_Todos,context.previousTodos)
} }); }export default useAddTodo
and I face error like this for mutationfn:
No overload matches this call.
The last overload gave the following error.
Object literal may only specify known properties, and 'mutationFn' does not exist in type 'readonly unknown[]'.ts(2769)
useMutation.d.ts(6, 25): The last overload is declared here.
and like this for onsuccess and onError functions input:
Parameter implicitly has an 'any' type
Does anyone know the solution?