Neal Rogers
Neal Rogers

Reputation: 500

How to use apolloClient's 'onSuccess' only once the useMutation has executed successfully

I need to be able to perform a function (closeModal), when the useMutation (insert/update query) executes with success, and before or on each reRender.

If I uncomment the code in the onClose function from the 'useMutation' function, then from the parent I can't open the modal (open close and toggle are handled by the parent, ..see beneath)

Modal child:

 export default function DeviceModal(props) {
    const device = useQuery(getDevice_query, {variables: {id: dataRowId}});
    const [dbUpdate,{ data, loading, error }] = useMutation(insertDevice_query,
    {
        //onSuccess: onClose(),
    });

    const onClose = () => {
        props.closeModal();
    };

return ( ModalMarkup );
}

Parent:

const [isModalShown, toggleModal] = React.useState(false);
const closeModal = () => {
    toggleModal(false)
}
const openModal = () => {
    toggleModal(true)
}

Upvotes: 0

Views: 2576

Answers (3)

Arslan Ali
Arslan Ali

Reputation: 448

You are passing the wrong option to the useQuery hook. There is no onSuccess parameter in appolo client v3. You need to replace it with onCompleted. Now whete you're using the useMutation or useQuery you should pass the onCompleted rather than onSucess. So your code will be look like this.

    export default function DeviceModal(props) {
    const device = useQuery(getDevice_query, {variables: {id: dataRowId}});
    const [dbUpdate,{ data, loading, error }] = useMutation(insertDevice_query,
    {
        onCompleted: ()=>{
         onClose();
    },
    });

    const onClose = () => {
        props.closeModal();
    };

      return ( ModalMarkup );
    }

Check here useQuery params.

Check here useMutation params.

Upvotes: 2

Neal Rogers
Neal Rogers

Reputation: 500

The answer is to use the return promise where the hook is called, i.e. use .then as below

const [dbUpdate,{ data, loading, error }] = useMutation(insertDevice_query);

const handleSubmit = (evt) => {
    evt.preventDefault();
    const deviceRec = recState;
    dbUpdate({ variables: {device: deviceRec}})
        .then( onClose() );
};

Upvotes: 0

Max Fahl
Max Fahl

Reputation: 888

One options is to pass a function as a prop to DeviceModal and then call it in your success handler. For example:

<DeviceModal closeModal={closeModal} />
onSuccess: props.closeModal()

Upvotes: 0

Related Questions