swifty
swifty

Reputation: 1147

Jotai with tanstack query isn't refetching after mutation

I have an example repo in which I have an API. The issue is, if I perform a mutation on my data, I have to refresh the page before I see the result.

The code is available on github: https://github.com/irvingswiftj/nextjs-jotai-query-example

The three key files are:

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>
  );
};

Upvotes: 0

Views: 217

Answers (0)

Related Questions