*설치할 것

yarn add axios
yarn add json-server

json-server --watch db.json --port 4000를 입력했더니
bash: json-server: command not found
떠서
npm install -g json-server 하고 다시

json-server --watch db.json --port 4000
썻더니 적용됐다
머여,,,; 이유는 모르겠다..

그럼 인사해준다 ㅋ.ㅋ

db.json 폴더를 하나 만들고 넣어준다.

{
    "todos": [
        {
            "id": 1,
            "title": "react"
        },
        {
            "id": 2,
            "title": "node"
        },
        {
            "id": 3,
            "title": "spring"
        }
        
    ] 
}
function App() {

  const fatchTodos = async () => {
    const response =  axios.get('http://localhost:4000/todos')
    console.log('response', response)
  }

  useEffect(() => {
    // db로부터 값을 가져올 것이다.
    fatchTodos()
  }, [])
  

  return (
    <div>
      axios
    </div>
  );
}

export default App;

여기서 consloe.log 확인을 하면 

pending이 찍힌 이유는 axious 요청을 한 직후에 찍혀 버리기 때문에 axious앞에 await문법 쓰면 async블록 안에서 

const {data} = await axios.get("http://localhost:4000/todos")

줄이 끝날 때까지 기다려준다 -> 정상적으로 값을 받을 수 있다.

여기서 data를 빼오자~~~~!

컴포넌트가 렌더링이 됐을 때 비동기함수가 실행되기 전에 return부분이 호출이 된다.

렌더링이 되고 나서 비동기함수가 async니까 타이밍이 더 늦다.

코드는 위에서부터 돌아가지만 async이기 때문에 fatchTodos 이 부분이 돌아갈 때까지 return이 기다리지 않는다.

그래서 todos는 없을수도 있는 현재 null일 수 있다. 그래서 todos? 해주면 된다!

'React' 카테고리의 다른 글

Redux-thunk (미들웨어)  (0) 2023.04.29
axios interceptor  (0) 2023.04.29
React Hooks - 최적화(React.memo, useCallback, useMemo)  (1) 2023.04.19
React Hooks - useRef  (0) 2023.04.19
React Hooks - useEffect  (0) 2023.04.19

+ Recent posts