带有 tanstack 查询的 Jotai 在突变后不会重新获取

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

我有一个示例存储库,其中有一个 API。问题是,如果我对数据执行突变,我必须刷新页面才能看到结果。

代码可在 github 上获取:https://github.com/irvingswiftj/nextjs-jotai-query-example

三个关键文件是:

store/contactsAtom.ts

import { atomWithMutation, atomWithQuery } from "jotai-tanstack-query";
import { useQueryClient } from "@tanstack/react-query";

export const contactsAtom = atomWithQuery(() => ({
  queryKey: ["contacts"],
  queryFn: async () => {
    const res = await fetch(`/api/contacts`);
    return res.json();
  },
}));

export const contactsMutation = atomWithMutation(() => ({
  mutationKey: ["contacts"],
  mutationFn: async (contacts) => {
    const res = await fetch(`/api/contacts`, {
      method: "POST",
      body: JSON.stringify(contacts),
    });
    const data = await res.json();
    return data;
  },
  onSuccess: (data, variables, context) => {
    const queryClient = useQueryClient();
    queryClient.invalidateQueries({
      queryKey: ["contacts"],
      refetchType: "all",
    });
  },
}));

export default contactsAtom;

app/page.tsx

"use client";

import contactsAtom, { contactsMutation } from "@/store/contactsAtom";
import { useAtom } from "jotai";

export default function Home() {
  const [{ data: contacts = [], isPending, isError }] = useAtom(contactsAtom);
  const [{ mutate, status }] = useAtom(contactsMutation);

  const handleAddContact = () => {
    mutate([
      ...contacts,
      {
        name: `test name ${new Date()}`,
        birthday: [1, 1, 2000],
        anniversary: [1, 2, 2000],
      },
    ]);
  };

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <span>Contacts: {contacts.length}</span>
      <a href="#" onClick={handleAddContact}>
        Add contact
      </a>
    </main>
  );
}

contexts/query-provider

"use client";

import { PropsWithChildren, Suspense } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Provider } from "jotai/react";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

const queryClient = new QueryClient();

export const QueryProvider = ({ children }: PropsWithChildren) => {
  return (
    <QueryClientProvider client={queryClient}>
      <Provider>
        {children}
        {/* <ReactQueryDevtools /> */}
      </Provider>
    </QueryClientProvider>
  );
};
reactjs typescript next.js tanstackreact-query jotai
1个回答
0
投票

有人找到这个问题的答案了吗?或者作者找到解决方案了吗?如果是的话请在这里发布解决方案

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