Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Last active May 31, 2020 12:38
Show Gist options
  • Save cameronp98/60ad9f6d3528528b0183f45b69690dae to your computer and use it in GitHub Desktop.
Save cameronp98/60ad9f6d3528528b0183f45b69690dae to your computer and use it in GitHub Desktop.
Async get for component data using axios and React Hooks
import axios from 'axios'
import { useEffect, useState } from 'react'
export default function(url) {
const [state, setState] = useState({ status: 'pending' })
useEffect(() => {
axios
.get(url)
.then((res) => {
setState({
status: 'ok',
data: res.data,
})
})
.catch((error) => {
setState({
status: 'error',
error,
})
})
}, [url])
return state
}
import React from 'react'
import useAsyncGet from '../asyncget'
const Foo = ({ fooId }) => {
const foo = useAsyncGet(`http://api.foo.org/${fooId}`)
if (foo.status === 'pending') {
return <div>Loading...</div>
}
if (foo.status === 'ok') {
return <div>{JSON.stringify(foo.data)}</div>
}
if (foo.status === 'error') {
console.error(foo.error)
return <div>Error fetching data.</div>
}
throw new Error(`Invalid fetch status: ${question.status}`)
}
export default Question
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment