Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@garahad
Last active October 15, 2019 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garahad/d4840bf85f4fbc752d23ca75217603ae to your computer and use it in GitHub Desktop.
Save garahad/d4840bf85f4fbc752d23ca75217603ae to your computer and use it in GitHub Desktop.
```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