Last active
April 19, 2020 12:26
-
-
Save safronman/90dac79ba3a5b92ed223d7ef01c23426 to your computer and use it in GitHub Desktop.
Кастомный хук useFetch
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 {useState, useEffect} from 'react' | |
| import axios from 'axios' | |
| export default url => { | |
| const baseUrl = 'https://conduit.productionready.io/api' | |
| const [isLoading, setIsLoading] = useState(false) | |
| const [response, setResponse] = useState(null) | |
| const [error, setError] = useState(null) | |
| const [options, setOptions] = useState({}) | |
| const doFetch = (options = {}) => { | |
| setOptions(options) | |
| setIsLoading(true) | |
| } | |
| useEffect(() => { | |
| if (!isLoading) { | |
| return | |
| } | |
| axios(baseUrl + url, options) | |
| .then(res => { | |
| setResponse(res.data) | |
| setIsLoading(false) | |
| }) | |
| .catch(error => { | |
| setError(error.response.data) | |
| setIsLoading(false) | |
| }) | |
| }, [isLoading]) | |
| return [{isLoading, response, error}, doFetch] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment