본문 바로가기

내배캠 4기 React - TIL

230117 TIL

비동기 통신
import "App.css";

// async, await
// then, catch, finally

function App() {
    // fetch 키워드를 이용해서...
    fetch("http://localhost:4000/posts/1")
        .then((response) => {
            // 정상인 경우
            console.log("response", response);
        })
        .catch((error) => {
            // 오류인 경우
            console.log("error", error);
        })
        .finally(() => {
            // 무조건 나옴
            console.log("무조건");
        });


    return <div>Hello React!!</div>;
}

export default App;

// 비동기 : 제어권이 넘어간 상태

// then : 정상인 경우 처리
// catch : 오류인 경우

// fetch("")
//     .then(() => {
// 정상인 경우
//     })
//     .catch(() => {
// 오류인 경우
//     }).finally(()=>{
// 무조건
// });

// then과 catch는 같이 써야한다.
import "App.css";
import axios from "axios";

function App() {
    axios
        .get("http://localhost:4000/posts/1")
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.log(error);
        });

    return <div>Hello React!!</div>;
}

export default App;
import "App.css";
import axios from "axios";

function App() {
    const fetchData = async () => {
        // 비동기 관련 로직
        const response = await axios.get("http://localhost:4000/posts/1");
        console.log("response", response);
    };

    fetchData();

    return <div>Hello React!!</div>;
}

export default App;


// async 함수는 await를 만나면 기다렸다가 내려간다.

'내배캠 4기 React - TIL' 카테고리의 다른 글

230130 TIL  (0) 2023.01.31
230119 TIL  (0) 2023.01.19
230116 TIL  (0) 2023.01.16
230113 TIL  (0) 2023.01.13
230110 TIL  (0) 2023.01.11