javascriptreactjsgraphqlapollo

How to call hook after delete mutation?


In my react app, I would like to navigate to another page after I execute GQL delete mutation using Apollo. This mutation is called from inside a modal popup:

function DeckDeleteModal({showModal, setShowModal, deckId}) {
  const [error, setError] = useState(null);
  const [deleteDeck, { loading }] = useMutation(DELETE_DECK, {
    onCompleted() { (Navigate("/decks")) },
    onError: (error) => { setError(error.graphQLErrors[0].message)}
  });

  if (error) {
    return <Alert variant="danger">error</Alert>
  }

  return (
    <Modal size="sm" variant="dark" centered show={showModal}>
      <Modal.Header>
        <Modal.Title id="contained-modal-title-vcenter">
          Delete deck?
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        Are you sure you want to delete this deck?
      </Modal.Body>
      <Modal.Footer>
        <Button variant="danger" disabled={loading} onClick={() => deleteDeck({ variables: { id: deckId} })}>
          { loading ? <Spinner size="sm" /> : <>Delete</>}
        </Button>
        <Button onClick={() => setShowModal(false)} variant="light">Close</Button>
      </Modal.Footer>
    </Modal>
  );
}

export default DeckDeleteModal;

The mutation finished successfully but I get the following error:

Invalid hook call. Hooks can only be called inside of the body of a function component.

What am I doing wrong?


Solution

  • Try to replace Navigate("/decks") with useNavigate from react-router-dom like this :
    const navigate = useNavigate();
    And then in onCompleted function call it:
    navigate("/decks");