フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

React Hooksでaxiosを利用して外部データを取得し表示する

はじめに

  • 下記のclientテスト用APIを利用してReactHooksからaxiosでリクエストしてデータを表示させる

Reqres - A hosted REST-API ready to respond to your AJAX requests

外部API

{"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"},{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve","last_name":"Holt","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"},{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles","last_name":"Morris","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"},{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey","last_name":"Ramos","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"}],"ad":{"company":"StatusCode Weekly","url":"http://statuscode.org/","text":"A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."}}

 方法①

下記のような方法でも取得することが可能である。下記の例はコンポーネント作成時のみ実行される

  useEffect( async () => {
    const result = await axios(
      'https://reqres.in/api/users?delay=1',
    ).then((response) => {
      setState({ ...state, data: response.data.data });
    })
  }, [])

画面上エラーはでないがconsole上ではエラーが発生している

Warning: An effect function must not return anything besides a function, which is used for clean-up.

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching

取得方法②

  • 下記の方法だと①のときのエラーは発生しない
  useEffect( () => {
    const fetchData  = async () => {
      const result = await axios(
        'https://reqres.in/api/users?delay=1',
      ).then((response) => {
        setState({ ...state, data: response.data.data });
      })
    }
    fetchData()
  }, [])
  • view側の処理は下記となりますが、正しくデータが表示されていることを確認できました。
        <Table striped bordered hover>
          <thead>
            <tr>
              <th>#</th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>email</th>
              <th>Avatar</th>
            </tr>
          </thead>
          <tbody>
            {
              state.data.map((d) => {
                return (
                    <tr>
                      <td>{d.id}</td>
                      <td>{d.first_name}</td>
                      <td>{d.last_name}</td>
                      <td>{d.email}</td>
                      <td><img src={d.avatar}/></td>
                    </tr>
                  );
              })
            }
          </tbody>
        </Table>

おすすめのパッケージ

  • 下記のパッケージを利用すると簡単に実装できそうでしたが、postできるかよくわかなかったので、今回は見送りました。使ってよかったという方がいましたら、教えてください。

GitHub - peng-yin/react-hooks-axios: ⚛️基于React Hooks使用axios获取数据