[Udemy] searching xx -5

이진경·2020년 5월 25일
0

Udemy

목록 보기
4/7

refactorying

  • now we've got to provide that autorization thing and that's really long url.
    all that stuff that propably should not belong directly inside of our app class.

  • to fix this stuff up i'm going to flip back over to the unsplash file.
    the nice thing about axios is that you can kind of set up a preconfigured instance of the axios client that has default properties set for where it's going to make a request to or headers and even params if you wanted to as well.

  • 우선, 권한부분과 url을 따로 분리하기 위해 하기와 같이 폴더를 나눈다

<unsplash.js>

import axios from 'axios';

export default axios.create({
// going to get route & url or just domain from App.js and paste as below

  baseURL: 'https://api.unsplash.com',
  headers: {
    Authorization: 'Client-ID Rw6et1-um043INr5rEgB3uiIeQHs_6LlF5UMrDcEUws',
  },
});

<App.js>

  • This is not going to completely clean up all the code inside of search submit or it's still going have to put a fair amount of configuration inside of your including having to specify some "params" so we could absolutely have clean this up more by creating a function.
    As i mentioned called like find me some pictures or writing or you want to call it. And then we could have completely isolated all this "axios" stuff into some separate file. Totally an option we could totally do that.
    But like i said taking this approach right here of creating a customized instance is going to have big benefits on some later app's were going to work on.
import React from 'react';
import unsplash from '../api/unsplash';
import SearchBar from './SearchBar';

class App extends React.Component {
  state = {
    images: [],
  };

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

    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;

  • 상위처럼 바꿔도 여전히 검색이 잘됨!

0개의 댓글