Last active
May 31, 2020 12:38
-
-
Save cameronp98/60ad9f6d3528528b0183f45b69690dae to your computer and use it in GitHub Desktop.
Async get for component data using axios and React Hooks
This file contains 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 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 | |
} |
This file contains 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 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