import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import Axios from "axios";
import "./styles.css";
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 url => {
try {
const { data } = await Axios.get(url);
throw Error();
setpayload(data);
} catch {
setError("fuck");
} finally {
setloading(false);
}
};
useEffect(() => {
callUrl();
}, []);
return { payload, loading, error };
}
function App() {
const name = useInput("");
const { payload, loading, error } = useFetch("https://aws.random.cat/meow");
return (
<div class Name="App">
<h1>Use Hooks</h1>
<br />
<input
value={name.value}
onChange={name.onChange}
placeholder="What your name"
/>
<br />
{loading && <span>loading your cat</span>}
{!loading && error && <span>{error}</span>}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
'REACT' 카테고리의 다른 글
LifeCycle API (1) (0) | 2020.12.02 |
---|---|
노마드코더 useState 예제 (0) | 2020.07.08 |
노마드 코더 state 와 componentDidMount와 componentDidUpdate 예제 (0) | 2020.07.01 |
노마드 코더 props , map 기본 예제 (0) | 2020.06.30 |
노마드 코더 props 기본 예제 (0) | 2020.06.30 |