RTK查询为什么不能实现自动刷新



我有以下问题。我在一个本地开发,我正在实现RTK查询,以向我的API提出请求。

一切都很好,但我遇到的问题是,当我想用providerTags实现自动refetch时。

如果我以以下方式处理代码,一切都会完美运行:


// todoApi.ts

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { Todo } from "../../models";
import { TodoCreateDTO } from "../../models/dto";
import { TodoUpdateDTO } from "../../models/dto/TodoUpdate.dto";
export const todoApi = createApi({
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:3000/",
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS, POST, GET, PUT, PATCH",
},
credentials: "include",
}),
tagTypes: ['Todos'],
endpoints: (builder) => ({
todos: builder.query<Todo[], void>({
query: () => ({
url: 'todos'
}),
providesTags: ['Todos'],
}),
todo: builder.query<Todo, number>({
query: (id) => ({
url: `todos/${id}`
}),
providesTags: ['Todos']
}),
createTodo: builder.mutation<Todo, TodoCreateDTO>({
query: (todo) => ({
url: 'todos',
method: "POST",
body: todo
}),
invalidatesTags: ['Todos']
}),
updateTodo: builder.mutation<Todo, TodoUpdateDTO>({
query: ({ id, ...todo }) => ({
url: `todos/${id}`,
method: "PATCH",
body: todo
}),
invalidatesTags: ['Todos']
}),
deleteTodo: builder.mutation<Todo, number>({
query: (id) => ({
url: `todos/${id}`,
method: "DELETE"
}),
invalidatesTags: ['Todos']
}),
}),
});

export const {
useTodosQuery,
useTodoQuery,
useCreateTodoMutation,
useUpdateTodoMutation,
useDeleteTodoMutation
} = todoApi


// Todos.tsx
import { useTodosQuery } from "../../app/services/todoApi"
import { TodoCard } from "./TodoCard";
export interface TodosProps {
}
export const Todos = () => {
const { data, error, isLoading, isFetching, isSuccess } = useTodosQuery();
return (
<>
{isLoading && <h2>... Loading</h2>}
{isFetching && <h2>... Fetching</h2>}
{error && <h2>Error</h2>}
{isSuccess && (
<>
{data.map(todo => (
<TodoCard
id={todo.id} />
))}
</>
)}
</>
)
}
// TodoCard
import { MButton, MCards } from "@inversiones-ma/finfast-react-controls";
import { useTodoQuery } from "../../app/services/todoApi";
export interface TodoCardProps {
id: number
};
export const TodoCard = ({ id }: TodoCardProps) => {
const { data } = useTodoQuery(id);
return (
<MCards className='p-4 mb-1' color="warning">
<h5 className="mb-0">{data?.title}</h5>
<p className="mb-0">{data?.description}</p>
<small className="text-muted">{data?.status ? "Finalizada" : "Pendiente"}</small>
<div>
<div className="btn-group">
<MButton color="success">Update</MButton>
<MButton color="error">Delete</MButton>
</div>
</div>
</MCards>
)
};

// CreateTodo
import { useForm, SubmitHandler } from "react-hook-form";
import { MButton, MCards, MInputGeneric, MSwitch } from "@inversiones-ma/finfast-react-controls";
import { useCreateTodoMutation, useTodosQuery } from "../../app/services/todoApi";
import { TodoCreateDTO, UserCreateDTO } from "../../models/dto";
type InputCreateTodo = {
title: string,
description: string,
status: boolean
};
export interface CreateTodoProps {
};
const user: UserCreateDTO = {
email: "email@email.com",
name: "My Name",
password: "mySecretPassword",
username: "myUsername"
};
export const CreateTodo = () => {
const [createTodo] = useCreateTodoMutation();
const {refetch} = useTodosQuery();
const form = useForm<InputCreateTodo>();
const { handleSubmit } = form;
const onSubmit: SubmitHandler<InputCreateTodo> = async (data) => {
let todo: TodoCreateDTO = {
title: data.title,
description: data.description,
status: data.status,
user
};
await createTodo(todo);
refetch()
}
return (
<MCards className='p-4'>
<h5>Create new todo</h5>
<form onSubmit={handleSubmit(onSubmit)}>
<MInputGeneric form={form} name={"title"} label={"Title"} ></MInputGeneric>
<MInputGeneric form={form} name={"description"} label={"Description"} ></MInputGeneric>
<div className="d-flex align-items-center">
<small className="mx-2">Finalizada</small>
<MSwitch form={form} name={"status"}></MSwitch>
</div>
<MButton type="submit" size="mini" className="w-100 mt-3">Create</MButton>
</form>
</MCards>
)
}

据我所知,每次我向查询添加providerTag时,通过向突变添加invalidTag,我都会使调用无效,并且应该执行自动引用。但这并没有发生,我已经想了一千次了,但我找不到解决方案,如果我在通过refetch((调用突变后,在CreateTodo.tsx组件中手动调用,一切都会得到解决。

有人看到我身上发生了什么事吗?我将不胜感激。

在@phry评论的帮助下,我找到了解决方案,结果发现在Redux存储中,我没有实例化todoAPI中间件。这是通过添加以下行来解决的:

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import { todoApi } from './services/todoApi';
export const store = configureStore({
reducer: {
[todoApi.reducerPath]: todoApi.reducer
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(todoApi.middleware)
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action<string>>;

谢谢!

相关内容

  • 没有找到相关文章

最新更新