Next.js Discord

Discord Forum

Unable to delete item from zustand store with React Query mutation in next 13

Unanswered
Golden-cheeked Warbler posted this in #help-forum
Open in Discord
Golden-cheeked WarblerOP
So I've been trying out new tech stack of zustand and react query with a todo app. The query and update mutation seems fine, the real problem is that the delete mutation seems to be caching, the item only disappear when I clear the cache via react query dev-tool and perfom another action or switch to another tab and switch back. Any idea what's happening?
  const queryClient = useQueryClient();

  const [todos, setTodos] = useTodoStore((state: any) => [
    state.todos,
    state.setTodos,
  ]);
  function getTodos() {
    return Promise.resolve(todos);
  }


  function deleteTodo(id: number) {
    const newTodos = todos.filter((todo: any) => todo.id !== id);
    setTodos(newTodos);
    return Promise.resolve(todos);
  }

  const { data, isLoading, isError } = useQuery({
    queryKey: ["todos"],
    queryFn: getTodos,
  });


  const deleteMutation = useMutation({
    mutationFn: (todo: any) => {
      return deleteTodo(todo.id);
    },
    onMutate(variables) {
      queryClient.invalidateQueries(["todos"]);
    },
    onSuccess: (id) => {
      queryClient.invalidateQueries(["todos"]); // Invalidate the entire todos list
    },
  });

This is the store
import { create } from "zustand";

const useTodoStore = create((set) => ({
  todos: [
    {
      id: 1,
      title: "delectus aut autem",
      description: "This is the first task",
      completed: false,
    },

  ],
  setTodos: (todos: any) => set({ todos }),
}));

export default useTodoStore;

0 Replies