Created
April 23, 2019 23:48
-
-
Save andycarrell/516ba910297e9707d2694f11c225254e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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