src/pages/client-fetching.js
// Example React custom hook to fetch data.
Example React custom hook to fetch data.
Example React custom hook to fetch data .
function fetchPupper() {
  let isCancelled = false
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(false)
  const [pupper, setPupper] = useState({
    img: '',
    breed: '',
  })
  const fetchPupper = async () => {
    setLoading(true)
    try {
      const {
        data: { message: img },
      } = await axios.get(`https://dog.ceo/api/breeds/image/random`)
      const breed = img.split('/')[4]
      if (!isCancelled) {
        setLoading(false)
        setPupper({
          img,
          breed,
        })
      }
    } catch (error) {
      if (!isCancelled) {
        setError(error)
        setLoading(false)
      }
    }
  }
  useEffect(() => {
    fetchPupper()
    return () => {
      isCancelled = true
    }
  }, [])
  return {
    loading,
    pupper,
    error,
  }
}
function fetchPupper ( ) { let isCancelled = false const [ loading , setLoading ] = useState ( false ) const [ error , setError ] = useState ( false ) const [ pupper , setPupper ] = useState ( { img : '' , breed : '' , } ) const fetchPupper = async ( ) => { setLoading ( true ) try { const { data : { message : img } , } = await axios . get ( ` ` ) const breed = img . split ( '/' ) [ 4 ] if ( ! isCancelled ) { setLoading ( false ) setPupper ( { img , breed , } ) } } catch ( error ) { if ( ! isCancelled ) { setError ( error ) setLoading ( false ) } } } useEffect ( ( ) => { fetchPupper ( ) return ( ) => { isCancelled = true } } , [ ] ) return { loading , pupper , error , } }
Example React custom hook to fetch data.
Example React custom hook to fetch data .