본문 바로가기

REACT

노마드코더 useState useEffect 예제

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);