English 中文(简体)
无效查询
原标题:Invalidate queries doesn t work [React-Query]

我试图每时让用户以“类似”的语气来回答所有询问,但迄今为止,尽管有该书,还是没有成功。

我有一个获得数据的构成部分:

  const {
    data: resultsEnCours,
    isLoading,
    isError,
  } = useQueryGetEvents("homeencours", { currentEvents: true });

这是一种习惯做法,可视此:

const useQueryGetEvents = (nameQuery, params, callback) => {
  const [refetch, setRefetch] = React.useState(null);
  const refetchData = () => setRefetch(Date.now()); // => manual refresh
  const { user } = React.useContext(AuthContext);
  const { location } = React.useContext(SearchContext);

  const { isLoading, isError, data } = useQuery(
    [nameQuery, refetch],
    () => getFromApi(user.token, "getEvents", { id_user: user.infoUser.id, ...params }),
    // home params => "started", "upcoming", "participants"
    {
      select: React.useCallback(({ data }) => filterAndSortByResults(data, location, callback), []),
    }
  );

  return { data, isLoading, isError, refetchData };
};

export default useQueryGetEvents;

我还有一个组成部分“ButtonLikeEvent”,使用户能够喜欢或不喜欢一件事:

import { useMutation, useQueryClient } from "react-query";
import { postFromApi } from "../../api/routes"; 
...other imports


const ButtonLikeEvent = ({ item, color = "#fb3958" }) => {
  const queryClient = useQueryClient();
  const {
    user: {
      token,
      infoUser: { id },
    },
  } = React.useContext(AuthContext);

  const [isFavorite, setIsFavorite] = React.useState(item.isFavorite);
  const likeEventMutation = useMutation((object) => postFromApi(token, "postLikeEvent", object));
  const dislikeEventMutation = useMutation((object) =>
    postFromApi(token, "postDislikeEvent", object)
  );

  const callApi = () => {
    if (!isFavorite) {
      likeEventMutation.mutate(
        { id_events: item.id, id_user: id },
        {
          onSuccess() {
            queryClient.invalidateQueries();
            console.log("liked");
          },
        }
      );
    } else {
      dislikeEventMutation.mutate(
        { id_events: item.id, id_user: id },
        {
          onSuccess() {
            queryClient.invalidateQueries();
            console.log("disliked");
          },
        }
      );
    }
  };

  return (
    <Ionicons
      onPress={() => {
        setIsFavorite((prev) => !prev);
        callApi();
      }}
      name={isFavorite ? "heart" : "heart-outline"}
      size={30}
      color={color} //
    />
  );
};

export default ButtonLikeEvent;

Every time an user click on that button I d like to invalidate queries (because many screens shows the like button).

The console. 记录显示是成功的,但查询并不无效。

任何想法?

感谢

问题回答

I 意外使用

const queryClient = new QueryClient();

而不是

const queryClient = useQueryClient();

<代码>new QueryClient(>>创建了一个新的反应频率客户(通常转至您的申请书上),这只应一次。

wheres useQueryClient returns a reference to the value that the react-query Client context wrapped around your app provides. You should use it inside your components.

此外,前面还没有提到另一个原因:

如果您使用<条码>,可在<条码>中选择<>。 。 摘自:

https://tanstack.com/query/latest/docs/react/guides/disabling-queries

问询将忽视质疑客户无效的问题。 问询和回费,通常会导致盘问。

The two most common issues why query invalidation is not working are:

  • 钥匙不匹配,因此,你试图使藏匿点中不存在的东西失效。 检查牛肉有助于这里。 通常,它是一个编号/范围的问题(例如,如果id是从ur里来的,那就是一种扼杀,但是在你的关键中,它有点)。 您还可以手工点击“invalidate, 纽扣在“devtools”上,因此,你将看到每件工程无效。

  • <编码>queryClient在累犯中并不稳定。 如果你在随后重新命名的部件的成文法内打上<条码>。 确保电离层稳定。

就我而言,我必须做的是等待以下承诺:invalidate Queries在脱机之前返回(使用反应路线)。

Samil和Eliav思想为我共同努力:

  1. QueryClient is only for initializing the QueryClientProvider.
const queryClient = new QueryClient();
  1. useQueryClient is used everywhere else.
const queryClient = useQueryClient();

在我的案件中,由于我试图使另一页使用的询问无效(使用Query,使用这个案件是没有的)。

我有两种解决办法:

  • use refetchInactive option like this: queryClient.invalidateQueries(key, { refetchInactive: true }), which will refetch the data instead of "stale" it.
  • use refetchOnMount: true option when calling useQuery, which will refetch the data on mount regardless if it is stale.

贵重物品应在贵方之首上公布。 (pp.js或index.js)

抽样

import { QueryClient, QueryClientProvider } from  react-query ;

const queryClient = new QueryClient();
ReactDOM.render(
    <QueryClientProvider client={queryClient}>
    <App />
    </QueryClientProvider>,
document.getElementById( root ));

我有同样的问题,就我而言,问题是我进口错误的客户。

我使用了自动填写码,并意外地从wagmi而不是@tanstack/react-query进口。

“enterography

在我的案件中,我试图在高于<代码>的构成部分中使用<代码>queryClient。 QueryClientProvider in the elementsmoto. 页: 1 h 载于<代码>总结的构成部分。 QueryClientProvider。

<MyFirstComponent> <!-- I was using it in My FirstComponent. It is outside the QueryClient Context so it is not going to work there -->
  <QueryClientProvider>
    <MySecondComponent /> <!-- You can use the queryClient here -->
  </QueryClientProvider>
</MyFirstComponent>

在我的案件中,invalidate Queries在坐标为 热载(改动后)之后没有工作。

非常令人厌恶的行为,但是,在你看到热负荷之前,它就是一种pri。

当使用<代码>ensure QueryData从海滩上检索数据(如果有的话)或以其他方式检索:一个令人感兴趣的挑战表面,<代码>invalidate Queries不会造成数据无效?

Thankfully, React Query has a different API for this particular situation:

queryClient.removeQueries({ queryKey: ["queryKey"] });

如果你在<条码>中恢复基于承诺的职能,那么你提出的问题可能不会被适当删除的另一个原因。 Fn 。

In my case, I made the mistake of calling the promise-based function without returning it. For example:

function useUpdateObject(id) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (newObj) => {
      // MISTAKE! Need to return ky.put(...)
      ky.put(API_ROUTE, { json: newObj }).json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["object", id],
      });
    },
  });
}

我也存在同样的问题,即一切都在当地正确工作,而不是生产。 问题在于我的Nginx服务器藏匿,无法更新数据。 为了确定这一点,我必须加上指令。

add_header  Cache-Control   no-cache  always;

纽约总部

我的问题是:

const { isLoading, data } = useQuery(
  CACHE_KEY,
  async () => apiFunction(foo)
);

事实上,我需要:

const { isLoading, data } = useQuery(
  CACHE_KEY,
  async () => await apiFunction(foo)
);

非常微妙和容易误导!





相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签