带有 tanstack 查询的 NextJs 14.1

问题描述 投票:0回答:1

在开发过程中,查询从数据库中获取数据并反映对数据库所做的任何更新。但是,构建应用程序后,查询检索到的数据将变为静态,即使对数据库进行更改也不会更新。

export const useGetAllList = () => {
  return useQuery({
    queryKey: ["ArLists"],
    queryFn: getAllList,
  });
};
export const getAllList = async () => {
  return (await axiosInstance.get<UserArList[]>("ar_lists/get_all_list")).data;
};

如何确保数据保持动态,即使在构建应用程序之后,数据库中发生更改时也会自动更新?

我是tanstack的新手,它在开发中工作正常,但是当我构建时,它没有改变数据,即使更新成功并在数据库中更新,但在UI中,它没有改变

tanstackreact-query nextjs14
1个回答
0
投票

尝试使用“useQueryClient”,通过发布请求进行更改:

import { useQueryClient } from "@tanstack/react-query";

const Component = () => {
 const queryClient = useQueryClient();

 const handleMakeChange = async () => {
  try {
  .......

  const response = await fetch("your/api/url", {
   method: "POST",
   ........, 
  });

  if (response.ok) {
  .......

  // Invalidate your queries to refetch the data for updating UI
  queryClient.invalidateQueries({ queryKey: ["ArLists"] });
  ......
   }}  
 };

return (
..... <>Your JSX elements</>
)}
export default Component;

确保您的 queryKey["ArLists"] 应与更新 UI 相同。

© www.soinside.com 2019 - 2024. All rights reserved.