Last active
October 15, 2019 13:39
-
-
Save garahad/d4840bf85f4fbc752d23ca75217603ae to your computer and use it in GitHub Desktop.
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
```javascript | |
import React, {useState, useEffect } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import Axios from 'axios'; | |
function useInput(defaultValue) { | |
const [value, setValue] = useState(defaultValue); | |
const onChange = e => { | |
const { | |
target: {value} | |
} = e; | |
setValue(value); | |
} | |
return {value, onChange}; | |
} | |
function useFetch(url) { | |
const [payload, setPayload] = useState(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(''); | |
const callUrl = async () => { | |
try { | |
const {data} = await Axios.get(url); | |
setPayload(data); | |
} catch { | |
setError('😵') | |
} finally { | |
setLoading(false) | |
} | |
} | |
useEffect(() => { | |
callUrl(); | |
}, []) | |
// 뒤에 []를 붙이면 mount때만 되고 update때는 되지 않게 말해주는 것. | |
return {payload, loading, error} | |
} | |
function App() { | |
const name = useInput(''); | |
const {payload, loading, error} = useFetch('https://~~~') | |
return ( | |
<div className = "app"> | |
<h1>use Hooks</h1> | |
<br/> | |
<input {...name} placeholder = "whats your name"/> | |
<br/> | |
{loading && <span>loading your cat</span>} | |
{!loading && error && <span>{error}</span>} | |
{!loading && payload && <img src={payload.file}, width="250" />} | |
</div> | |
) | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment