개인공부/TIL(Today I Learned)

TIL 70일차_리액트: fetch로 받아온 데이터 주의점

soon327 2021. 3. 29. 01:25

fetch로 받아왔을 때 주의점

  1. API에 접근해서 데이터를 받아오는 등의 동기적으로 이루어져야하는 함수는 componentDidMount()에서 실행한다.
  2. 이렇게 받은 데이터로 바꾼 state는 네트워크 속도가 아무리 빠르더라도 초기값을 바꾸지는 못하므로 처음렌더됐을때는 변화된 state값을 반영하지 못한다.
    따라서 해당 state를 사용하여 렌더할때는, default값을 주어야 TypeError가 뜨지 않는다.
class App extends Component {
  state = {
    customers: '',
  };

  //일반적으로 API에 접근을해서 데이터를 받아오는 등의 작업은 componentDidMount()에서 한다.
  //이 함수는 모든 컴포넌트가 마운트 되었을때 실행된다. 라이프사이클 참고.
  componentDidMount() {
    this.callApi()
      .then((res) => this.setState({ customers: res }))
      .catch((err) => console.log('componentDidMount_callAPI err', err));
  }

  callApi = async () => {
    const URL = 'http://localhost:5000/api/cutomers';
    const response = await fetch(URL);
    const body = await response.json();
    return body;
  };

  //아무리 네트워크 속도가 빠르더라도
  //처음 this.state.cutomers의 값은 ''이므로 default값을 지정해줘야한다.
  //안그러면 에러메시지 뜸 TypeError: this.state.customers.map is not a function
  render() {

    (...생략)

    {this.state.customers ? 
            this.state.customers.map((customer) => {
         const { id, image, name, age, gender } = customer;
         return <Customer key={id} id={id} image={image} 
        name={name} age={age} gender={gender} />;
       })
     : ''}
    }
}