Created
August 9, 2021 09:55
-
-
Save yilmazcakmakci/df632767117c2d4e23f6b55a442dda81 to your computer and use it in GitHub Desktop.
A React hook for handle different states on async requests without useState in component.
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 { useEffect, useState, useCallback } from 'react' | |
| const useFetch = (fetcher, { params = {}, immediate = false } = {}) => { | |
| const [loading, setLoading] = useState(false) | |
| const [data, setValue] = useState(null) | |
| const [error, setError] = useState(null) | |
| const execute = useCallback( | |
| (executeParams) => { | |
| setLoading(true) | |
| setValue(null) | |
| setError(null) | |
| return fetcher(executeParams ? executeParams : params) | |
| .then((response) => { | |
| setValue(response) | |
| }) | |
| .catch((error) => { | |
| setError(error) | |
| }) | |
| .finally(() => { | |
| setLoading(false) | |
| }) | |
| }, | |
| [fetcher] | |
| ) | |
| useEffect(() => { | |
| if (immediate) { | |
| execute() | |
| } | |
| }, [execute, immediate]) | |
| return [loading, data, error, execute] | |
| } | |
| export default useFetch | |
| /* | |
| Usage | |
| const [loading, todos, error, fetchTodos] = useFetch(_getTodos, { | |
| params: { id: 2 }, | |
| immediate: true, | |
| }) | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment