fetch

Seunghyunkim1·2020년 5월 3일

wecode

목록 보기
19/25

codesandbox

import "./styles.css";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      categories: []
    };
  }
  componentDidMount() {
    fetch("https://api.kurly.com/v2/categories?ver=1")
      .then(res => res.json())
      // .then(res => {
      //   console.log(res);
      //   return res.json();
      // })
      .then(res => {
        console.log(res.data.categories);
        this.setState({
          categories: res.data.categories
        });
      });
  }
  login() {
    fetch("https://api.kurly.com/login", {
      method: 'post',
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password
      })
    })
    .then(res => {
      if(res.status === 200) {
        this.props.history.push('/main')
      } else if (res.status === 403){
        alert("email fail")
      }
      return res.json()
    })
  }
  render() {
    return (
      <div className="App">
        <h1 onClick={this.login}>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <ul>
          {this.state.categories.map(el => (
            <li>{el.name}</li>
          ))}
        </ul>
      </div>
    );
  }
}
export default App;

렌더링된 하면을 조작해야한다

데이터를 준비안된상태에서 조작하면 안됨.

컨스럭터보다는 안전하게 렌더한후에 컴디마

동기
천개의 배열을 돌려도 천개가 끝날떄까지 기달렷다가 넘어감

비동기
아직 안끝나도 다음줄로 넘어감
fetch(자스 내장함수)비동ㄱㅣ 인터넷이 느리고 데이터가 많을때 api응답을 계속기다릴수없음
api의 요청후 기다리지않고 다음일을 함.
객체를 응답함.
.으로 접근 (.then)
프로미스 라는 객체를 반환함.
상태만 알려주는 객체 현상황 그안에 then함수잇음
then 앞에서 시킨거끝나면 그다음에 작동하는 함수
두번째 then도 프로미스객체반환 (그안에 then함수 - 그이전fetch끝나면 실행함)

.then(res => res.json()) 인자가 함수일때 --> 콜백함수 d

콘솔로그, 응답에 대한 모든정보 (코드로 응답)이 포함된다.

응답바디 --> 커피정보들 ( http복습할것)
res.body로 접근불가
res.json으로 호출해야만 body로접근가능

0개의 댓글