1
export const useDeleteArticles = ({ ids, onSuccess }) => {
  const queryResult = useQueries(
    ids.map(id => ({
      queryKey: ["article-delete", id],
      queryFn: () => articlesApi.destroy(id),
    }))
  );

  const isLoading = queryResult.some(result => result.isLoading);

  if (!isLoading) {
    onSuccess();
  }

  return { isLoading, queryResult };
};

This customHook will simply delete some articles.

I tried to use enabled with a state as following.

export const useDeleteArticles = ({ ids, onSuccess, enabled }) => {
  const queryResult = useQueries(
    ids.map(id => ({
      queryKey: ["article-delete", id],
      queryFn: () => articlesApi.destroy(id),
      enabled,
    }))
  );

  const isLoading = queryResult.some(result => result.isLoading);

  if (!isLoading) {
    onSuccess();
  }

  return { isLoading, queryResult };
};
const [enabled, setEnabled] = useState(false);
useDeleteArticles({ ids, onSuccess: refetch, enabled });

enabled && setEnabled(false);    //to avoid api call after deleting the articles

const handleArticleDelete = () => {    //this function will invoke onClick button
    setEnabled(true);
};

But this not making the api call. could anyone help me to implement this in correct way.

Thank you.

  • Does this answer your question? [React-Query: How to useQuery when button is clicked](https://stackoverflow.com/questions/62340697/react-query-how-to-usequery-when-button-is-clicked) – Konrad Dec 04 '22 at 14:34
  • 3
    Isn't [useMutation](https://react-query-v3.tanstack.com/guides/mutations) more suitable for your purposes? – Arturo Mendes Dec 04 '22 at 14:42

1 Answers1

0

This customHook will simply delete some articles.

a delete operation is almost never a query, but a mutation. Mutations can be fired imperatively by calling the mutate function returned from useMutation. A query is the wrong thing to use for this.

TkDodo
  • 20,449
  • 3
  • 50
  • 65