How to redirect to homepage using React Router and React Query

Viewed 1523

I have an app that displays a list of invoices. On clicking through to an individual invoice page, you have the option to delete that invoice. On clicking delete, a modal pops up to confirm the delete and the invoice is then removed from the list.

I am using React Router to navigate the pages in the app and React Query to handle the API interaction.

In the code below I am trying to delete an invoice using useMutation and invalidateQueries so that the list of invoices is updated, and then redirect to the homepage where all of the invoices are listed using Redirect.

The problem I'm having is that the Redirect seems to be happening before the queries are invalidated, so when I return to the list the deleted item is still appearing until you refresh the page. Is there any way around this?

import React, { useState } from "react";
import { useStore } from "../store";
import { deleteInvoice } from "../Api/ApiCalls";
import { useMutation, QueryClient } from "react-query";
import { Redirect } from "react-router-dom";

export default function DeleteModal({ id }) {
  const [redirect, setRedirect] = useState(false);
  const { setDeleteModal } = useStore();
  const queryClient = new QueryClient();

  const mutation = useMutation(deleteInvoice, {
    isSuccess: () => {
      queryClient.invalidateQueries("invoices");
    },
  });

const removeInvoice = () => {
    mutation.mutate(id)
    setRedirect(true)
}

  return (
    <div>
      <div className="delete-modal">
        <h1>Confirm Deletion</h1>
        <p>
          Are you sure you want to delete #{id}? This action cannot be undone
        </p>
        <button onClick={() => setDeleteModal(false)}>Cancel</button>
        <button onClick={() => removeInvoice()}>Delete</button>
        {redirect && <Redirect to="/" />}
      </div>
    </div>
  );
}
1 Answers

The useMutation hook returns some boolean variables you can use.

const mutation = useMutation(deleteInvoice, {
    onSuccess: () => {
      queryClient.invalidateQueries("invoices");
    },
  });

const removeInvoice = () => {
    mutation.mutate(id)
}

if (mutation.isSuccess) {
    return <Redirect to='/' />
}

return (
....
)
Related