How to use the react-query.useMutation function in react-query

To help you get started, we’ve selected a few react-query examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / library / management / loans / LoansTable.tsx View on Github external
loanableId,
  apiParameters,
}: {
  loanableId: string;
  apiParameters?: Partial;
}) => {
  const { sendInfoToast, sendSuccessToast, sendErrorToast } = useContext(
    ToastContext
  );

  // The loan edited in the modal.
  const [editLoan, setEditLoan] = useState(null);

  const { columns, sorting } = useColumns(columnsDefinition(setEditLoan));

  const [edit] = useMutation(api.loans.patch, {
    onMutate: () => sendInfoToast("Modification en cours…"),
    onSuccess: () => {
      sendSuccessToast("Modifications enregistrées !");
      queryCache.invalidateQueries("loans.list");
      setEditLoan(null);
    },
    onError: () => sendErrorToast("Une erreur est survenue."),
  });

  // Submit the form in the modal.
  const submit = (values, { setSubmitting }) => {
    if (editLoan) {
      if (values.status !== "RETURNED") {
        // `realReturnDate` may only change when the loanable returns.
        values.realReturnDate = null;
github tannerlinsley / react-query / examples / focus-refetching / pages / index.js View on Github external
export default () => {
  const { data, isLoading } = useQuery('user', () => fetch('/api/user'))

  const [logoutMutation] = useMutation(logout, {
    refetchQueries: ['user'],
  })

  const [loginMutation] = useMutation(login, {
    refetchQueries: ['user'],
  })

  if (isLoading) return <h1>Loading...</h1>
  if (data &amp;&amp; data.loggedIn) {
    return (
      <div>
        <h1>Welcome, {data.name}</h1>
        <img width="{80}" src="{data.avatar}">
        <button> {
            logoutMutation()</button></div>
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / polls / submit / SubmitPoll.tsx View on Github external
export const SubmitPoll = () => {
  const { sendSuccessToast, sendErrorToast } = useContext(ToastContext);
  const [create] = useMutation(api.polls.create, {
    onSuccess: () => {
      queryCache.invalidateQueries(["polls.list"]);
      queryCache.invalidateQueries(["polls.stats"]);
      sendSuccessToast("Sondage envoyé.");
    },
    onError: (errorAsUnknown) => {
      const error = errorAsUnknown as AxiosError;
      sendErrorToast(
        `Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${
          error.response === undefined
            ? ""
            : "Détails :" + error.response.data.detail
        }`
      );
    },
  });
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / page / create / AssociationCreatePage.tsx View on Github external
export const AssociationCreatePage = ({
  association,
}: {
  association: Association;
}) => {
  const { sendInfoToast, sendSuccessToast, sendErrorToast } = useContext(
    ToastContext
  );

  const history = useHistory();

  const [create] = useMutation(api.pages.create, {
    onMutate: () => sendInfoToast("Sauvegarde en cours…"),
    onSuccess: () => {
      sendSuccessToast("Page créée.");
      history.push(`/associations/${association.id}`);
      return queryCache.refetchQueries("pages.list");
    },
    onError: (errorAsUnknown) => {
      const error = errorAsUnknown as AxiosError;
      sendErrorToast(
        `Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${
          error.response
            ? "Détails : " +
              (error.response.status === 403
                ? "vous n’avez pas le droit de créer de page."
                : error.response.data.detail)
            : ""
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / events / create / AssociationCreateEvent.tsx View on Github external
export const AssociationCreateEvent = ({
  association,
}: {
  association: Association;
}) => {
  const { sendSuccessToast, sendErrorToast } = useContext(ToastContext);
  const [create] = useMutation(api.events.create, {
    onSuccess: (response) => {
      queryCache.refetchQueries(["events.list"]);
      sendSuccessToast("Événement créé.");
    },
    onError: (errorAsUnknown) => {
      const error = errorAsUnknown as AxiosError;

      sendErrorToast(
        `Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${
          error.response === undefined
            ? ""
            : "Détails : " + JSON.stringify(error.response.data)
        }`
      );
    },
  });
github tannerlinsley / react-query / examples / sandbox / src / index.app.js View on Github external
function AddTodo() {
  const [name, setName] = React.useState("");

  const [mutate, { isLoading, error, data }] = useMutation(postTodo, {
    refetchQueries: ["todos"]
  });

  return (
    <div>
      <input value="{name}"> setName(e.target.value)}
        disabled={isLoading}
      /&gt;
      <button> mutate({ name })} disabled={isLoading || !name}&gt;
        Add Todo
      </button>
      <div>
        {isLoading
          ? "Saving..."</div></div>
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / page / edit / AssociationEditPage.tsx View on Github external
`Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${
          error.response
            ? "Détails : " +
              (error.response.status === 403
                ? "vous n’avez pas le droit de modifier cette page."
                : error.response.status === 400 &&
                  error.response.data.nonFieldErrors
                ? "une page avec ce nom existe déjà."
                : JSON.stringify(error.response.data))
            : ""
        }`
      );
    },
  });

  const [remove] = useMutation(api.pages.delete, {
    onMutate: () => sendInfoToast("Suppression en cours…"),
    onSuccess: () => {
      sendSuccessToast("Page supprimée.");
      return queryCache
        .invalidateQueries("pages.list")
        .then(() => history.push(`/associations/${association.id}/pages`));
    },
    onError: (errorAsUnknown) => {
      const error = errorAsUnknown as AxiosError;
      sendErrorToast(
        `Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${
          error.response
            ? "Détails : " +
              (error.response.status === 403
                ? "vous n’avez pas le droit de supprimer cette page."
                : error.response.data.detail)
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / marketplace / counter / RefundForm.tsx View on Github external
export const RefundForm = ({ customer, marketplaceId, ...props }) => {
  const { sendSuccessToast, sendErrorToast } = useContext(ToastContext);
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  const [createFunding] = useMutation(api.fundings.create, {
    onSuccess: async () => {
      sendSuccessToast(`Solde mis à jour`);
      setShow(false);
      await queryCache.invalidateQueries("marketplace.balance");
    },
    onError: (err) => {
      sendErrorToast(`Erreur lors du passage de la commande : ${err}`);
    },
  });

  const increaseBalance = ({ refund }) => {
    createFunding({
      marketplaceId,
      customerId: customer.id,
      value: refund,
    });
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / library / home / LoanableCard.tsx View on Github external
cardStatus = false,
  className = "",
}: {
  loanable: Loanable;
  loanButton?: boolean;
  editButton?: boolean;
  comment?: boolean;
  cardStatus?: boolean;
  className?: string;
}) => {
  const user = useContext(UserContext);
  const { sendInfoToast, sendSuccessToast, sendErrorToast } = useContext(
    ToastContext
  );

  const [create] = useMutation(api.loans.create, {
    onMutate: () => sendInfoToast("Demande en cours d’envoi..."),
    onSuccess: () => {
      sendSuccessToast("Demande envoyée.");
      queryCache.invalidateQueries("loanables.list");
    },
    onError: () => sendErrorToast("La demande a échoué."),
  });

  const [cancel] = useMutation(api.loans.cancel, {
    onMutate: () => sendInfoToast("Annulation en cours..."),
    onSuccess: () => {
      sendSuccessToast("Demande annulée.");
      queryCache.invalidateQueries("loanables.list");
    },
    onError: () => sendErrorToast("L’annulation a échoué."),
  });
github Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / settings / namespace / CreateNamespaceForm.tsx View on Github external
export const CreateNamespaceForm = ({ association }) =&gt; {
  const { sendSuccessToast, sendErrorToast } = useContext(ToastContext);

  const [createNamespace] = useMutation(api.namespaces.create, {
    onSuccess: (response) =&gt; {
      queryCache.invalidateQueries(["association.namespaces.list"]);
      sendSuccessToast("Namespace ajouté");
    },
    onError: (errorAsUnknown) =&gt; {
      const error = errorAsUnknown as AxiosError;
      sendErrorToast(
        `Erreur. Merci de réessayer ou de contacter les administrateurs si cela persiste. ${error.message}`
      );
    },
  });

  return (
     {
        createNamespace({