React - Request - 07
Making API Requests with React
Axios vs Fetch
Handling Requests with Async Await
비동기식 코드를 동기식(코드 순서대로)으로 바꾸려면 es5에서는 promise/then을 사용하지만, es6부터는 async/await를 사용한다.
axios. get ( 'https://api/unsplash.com/search/photos' , {
params: { query: term } ,
headers: {
Authorization: 'Client-ID YOUR-ACCESS-KEY'
}
} ) . then ( response => {
console. log ( response. data. results) ;
} ) ;
async onSearchSubmit ( term) {
const response = await axios. get ( 'https://api/unsplash.com/search/photos' , {
params: { query: term } ,
headers: {
Authorization: 'Client-ID YOUR-ACCESS-KEY'
}
} ) ;
console. log ( response. data. results) ;
}
Binding Callbacks
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 } ) ;
}
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
onSearchSubmit = async term => {
const response = await unsplash. get ( '/search/photos' , {
params: { query: term }
} ) ;
this . setState ( { images: response. data. results } ) ;
}
import axios from 'axios' ;
export default axios. create ( {
baseURL: 'https://api/unsplash.com' ,
headers: {
Authorization: 'Client-ID YOUR-ACCESS-KEY'
}
} ) ;
Rendering Lists of Components
< ImageList images= { this . state. images} / >
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
댓글
댓글 쓰기