React - Request - 07

React - Request - 07

Making API Requests with React

Axios vs Fetch

  • axios: 3rd party package
  • fetch: function built into modern browsers
     npm install --save axios
    
     axios.get('https://api/unsplash.com/search/photos', {
      params: { query:  term },
      headers: {
       Authorization:  'Client-ID YOUR-ACCESS-KEY'
     }
    });
    

Handling Requests with Async Await

비동기식 코드를 동기식(코드 순서대로)으로 바꾸려면 es5에서는 promise/then을 사용하지만, es6부터는 async/await를 사용한다.
// es5
axios.get('https://api/unsplash.com/search/photos', {
 params: { query:  term },
 headers: {
  Authorization:  'Client-ID YOUR-ACCESS-KEY'
 }
}).then(response  => { // this
 console.log(response.data.results);
});

// es6
async  onSearchSubmit(term) { // async keyword
 const  response = await  axios.get('https://api/unsplash.com/search/photos', { // await keyword
  params: { query:  term },
  headers: {
   Authorization:  'Client-ID YOUR-ACCESS-KEY'
  }
 });

console.log(response.data.results);
}

Binding Callbacks

// App.js
import  React  from  'react';
import  axios  from  'axios';
import  SearchBar  from  './SearchBar';
  
class  App  extends  React.Component {
 state = { images: [] };
  
 async  onSearchSubmit(term) {
  const  response = await  axios.get('https://api/unsplash.com/search/photos', {
   params: { query:  term },
   headers: {
    Authorization:  'Client-ID YOUR-ACCESS-KEY'
   }

  });

  this.setState({ images:  response.data.results }); // this
 }

 render() {
  return (
   <div  className="ui container"  style={{ marginTop:  '10px' }}>
    <SearchBar  onSubmit={this.onSearchSubmit} />
Found: {this.state.images.length} images
   </div>
  );
 }
};
 
export  default  App;
데이터를 가져와서 setState하는 부분에서 this.setState is undefined라는 에러가 난다. console.log(this)를 출력해보면 onSearchSubmit()함수를 가리킨다. 따라서 onSearchSubmit() 함수에서 setState를 하려면 class App애 접근해야 하므로 아래와 같이 수정한다.
onSearchSubmit = async  terms  => {...}

Creating Custom Clients

// App.js
onSearchSubmit = async  term  => {
 const  response = await  unsplash.get('/search/photos', {
  params: { query:  term }
 });

 this.setState({ images:  response.data.results });
}

// unsplash.js
import  axios  from  'axios';

export  default  axios.create({
 baseURL:  'https://api/unsplash.com',
 headers: {
  Authorization:  'Client-ID YOUR-ACCESS-KEY'
 }
});

Rendering Lists of Components

// App.js
<ImageList  images={this.state.images} />

// ImageList.js
import  React  from  'react';

const  ImageList = props  => {
 console.log(props.images);
 return  props.images.map((image) => {
  return <img  src={image.urls.regular} />
 });
};

export  default  ImageList;
Error: Eash child in an array or iterator should have a unique “key” prop.

Implementing Keys in Lists

return  props.images.map(image  => {
 return <img  key={image.id} src={image.urls.regular} />
});

GitHub and Others

  • 강의를 들으며 따라한 내용을 pics에 올려두었습니다.
  • photo-engine

댓글

가장 많이 본 글