ブログの投稿ログ

2021年
9月
8月
7月
6月

初めてのREACT-v10

Reactでaxiosを使ったAPIの出力

前回のコードを引き続き使っていこうと思います。
ユーザーの入力を読み取れるようになったので、githubAPIからデータを引っ張ってきてそれらをブラウザで利用可能なフェッチを呼び出し、
AJAXで実装したいと思います。

JSX,REACT,REACT DOMが既に入っているこちらのIDEを使って一緒に進めていくとやりやすいです。 https://jscomplete.com/playground

今回のコード

// gaearon, sophiebits, sebmarkbage, bvaughn

const CardList = (props) => (
	<div>
  	{props.profiles.map(profile => <Card {...profile}/>)}
	</div>
);

class Card extends React.Component {
	render() {
  	const profile = this.props;
  	return (
    	<div className="github-profile">
    	  <img src={profile.avatar_url} />
        <div className="info">
          <div className="name">{profile.name}</div>
          <div className="company">{profile.company}</div>
        </div>
    	</div>
    );
  }
}

class Form extends React.Component {
	state = { userName: '' };
	handleSubmit = async (event) => {
  	event.preventDefault();
    const resp = await axios.get(`https://api.github.com/users/${this.state.userName}`);
    this.props.onSubmit(resp.data);
    this.setState({ userName: '' });
  };
	render() {
  	return (
    	<form onSubmit={this.handleSubmit}>
    	  <input 
          type="text" 
          value={this.state.userName}
          onChange={event => this.setState({ userName: event.target.value })}
          placeholder="GitHub username" 
          required 
        />
        <button>Add card</button>
    	</form>
    );
  }
}

class App extends React.Component {
  state = {
    profiles: [],
  };
  addNewProfile = (profileData) => {
    this.setState(prevState => (
      {
          profiles: [...prevState.profiles, profileData],
      }
    ));
  };
	render() {
  	return (
    	<div>
    	  <div className="header">{this.props.title}</div>
        <Form onSubmit={this.addNewProfile} />
        <CardList profiles={this.state.profiles} />
    	</div>
    );
  }	
}

ReactDOM.render(
	<App title="The GitHub Cards App" />,
  mountNode,
);

エンドポイント読み込み

handleSubmit = async (event) => {
  event.preventDefault();
  const resp = await axios.get(`https://api.github.com/users/${this.state.userName}`);
  this.props.onSubmit(resp.data);
  this.setState({ userName: '' });
};

まず、axios.get内にエンドポイトを設定します。[githubAPI](https://api.github.com/users) Axios.getはpromiseを返すのでawaitを使い変数のrespを返します。 この待機を機能させるためにhandleSubmitの関数にasyncをつける必要があります。 テキストボックスからの入力されて値をエンドポイントの末尾に付けたいので、${this.state.userName}を付け加えます。 試しにconsole.log(resp.data);を記入し、ブラウザのテキストボックスに文字を入れて送信するとデータをフェッチしていることが確認できるかと思います。

取得した配列をstate.profilesに受け渡す。

class App extends React.Component {
  state = {
    profiles: [],
  };
  addNewProfile = (profileData) => {
    this.setState(prevState => (
      {
          profiles: [...prevState.profiles, profileData],
      }
    ));
  };
	render() {
  	return (
    	<div>
    	  <div className="header">{this.props.title}</div>
        <Form onSubmit={this.addNewProfile} />
        <CardList profiles={this.state.profiles} />
    	</div>
    );
  }	
}

Formコンポーネントは状態要素(ここではprofiles)に直接アクセスできません。
これはReactには一方向のデータフローがあり、親コンポーネントであるAppコンポーネント内の状態を変更できないからです。
なので、Appコンポーネント内へprofilesの変更を書き加えていきます。

  addNewProfile = (profileData) => {
    this.setState(prevState => (
      {
          profiles: [...prevState.profiles, profileData],
      }
    ));
  };

addNewProfileという関数を定義して仮引数としてprofileDataを渡してあげます。
this.props.onSubmit(resp.data);でAPIの中身が仮引数に入っている状態でprofilesへ追加してあげる必要があります。
そこでsetState()を使用します。

 profiles: [...prevState.profiles, profileData],

...prevState.profiles,スプレッド構文を使って既に入っている値を展開して、profileDataでテキストボックスへ入力された新規の値が入ることになります。

ここで、テキストボックスへ任意の名前を入れてadd cardを押すと出力されることが確認できるかと思います。

以上で今日のお勉強を終わりたいと思います。