Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created April 23, 2019 23:48
Show Gist options
  • Save andycarrell/516ba910297e9707d2694f11c225254e to your computer and use it in GitHub Desktop.
Save andycarrell/516ba910297e9707d2694f11c225254e to your computer and use it in GitHub Desktop.
import { useCallback, useState } from "react";
export default function useMutation(mutate) {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const runMutation = useCallback(
(...args) => {
setIsLoading(true);
setError(null);
setData(null);
return mutate(...args)
.then(d => {
setData(d);
setError(null);
setIsLoading(false);
})
.catch(err => {
setError(err);
setData(null);
setIsLoading(false);
});
},
[mutate, setIsLoading, setError, setData],
);
return { isLoading, error, data, runMutation };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment