Last active
November 28, 2019 17:44
-
-
Save satishbabariya/21cb1f8aa567604e6ff334f32fc30f80 to your computer and use it in GitHub Desktop.
Using the State Hook
This file contains hidden or 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 {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> | |
); | |
}; |
This file contains hidden or 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, { 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