0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【React】axiosのgetを使ってみる

Last updated at Posted at 2021-05-24

細かい書き方は正しくないかもしれませんが、一旦getできたのでメモとして。
Someというコンポーネントを作成し、その中でaxios.get()を使っています。

Some.tsx
import React from 'react';
import axios from 'axios';

interface SomeResponse {
  id: number;
  title: string;
  ...
}

export default class Some extends React.Component {
  clicked() {
    axios.get<SomeResponse[]>('https://hogehoge.com/api/fugafuga')
      .then(res => {console.table(res.data)})
      .catch(error => {console.log(error)})
  }

  render() {
    return (
      <button onClick={this.clicked}>click</button>
    );
  }
}

取得したデータの型をSomeResponseという名前でinterfaceとして定義しておき、
axios.getの後ろにジェネリックとして渡します。

axios.get()の返り値はPromise型なので、後ろに.then().catch()を付けられます。

http通信のレスポンスにはdataプロパティが含まれているので、
それをconsole.table()に渡すことでデベロッパーツールのコンソールに表形式で出力します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?