Skip to content

Instantly share code, notes, and snippets.

@safronman
Last active April 19, 2020 12:26
Show Gist options
  • Select an option

  • Save safronman/90dac79ba3a5b92ed223d7ef01c23426 to your computer and use it in GitHub Desktop.

Select an option

Save safronman/90dac79ba3a5b92ed223d7ef01c23426 to your computer and use it in GitHub Desktop.
Кастомный хук useFetch
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