Skip to content

Instantly share code, notes, and snippets.

@satishbabariya
Last active November 28, 2019 17:44
Show Gist options
  • Save satishbabariya/21cb1f8aa567604e6ff334f32fc30f80 to your computer and use it in GitHub Desktop.
Save satishbabariya/21cb1f8aa567604e6ff334f32fc30f80 to your computer and use it in GitHub Desktop.
Using the State Hook
import {useAsync} from 'react-use';
const Demo = ({url}) => {
const state = useAsync(async () => {
const response = await fetch(url);
const result = await response.text();
return result
}, [url]);
return (
<div>
{state.loading
? <div>Loading...</div>
: state.error
? <div>Error: {state.error.message}</div>
: <div>Value: {state.value}</div>
}
</div>
);
};
import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import Progress from './Progress'
const callFakeAPI = delay =>
new Promise(resolve => {
setTimeout(resolve, delay)
})
const App = () => {
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
;(async () => {
await callFakeAPI(3000)
setIsLoading(false)
})()
}, [])
return (
<React.Fragment>
<Progress isAnimating={isLoading} />
<h1>{isLoading ? 'Loading...' : 'Loaded!'}</h1>
</React.Fragment>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment