Next.js で Axios , fetcher の非同期通信を便利にする SWR を使用する

● SWR を使用する

・1. swrとaxiosのインストール

yarn add swr
yarn add axios @types/axios

または

npm i swr -S

・2. fetcherの定義

import useSWR from 'swr'

fetchを使用する場合 の fetcher の定義方法

const fetcher = (url) => fetch( url )
  .then(res => res.json());

axiosを使用する場合 の fetcher の定義方法**

const fetcher = (url: string) => axios(url)
  .then((res) => {
    return res.data
  });

・3. NewsIndexコンポーネントの作成

function NewsIndex() {
  const { data, error } = useSWR('https://YOUR/SERVER/PATH/api/news/', fetcher)
    // swrによるfetchエラー時
  if (error) return <div>failed to load</div>
  // swrによるfetchロード中
  if (!data) return <div>now loading...</div>
  return (
    <ul>
    {data.map((v) => 
      <li key={v.id}>{v.id} : {v.name}</li>
    )}
  </ul>
  );
}

・4. NewsIndexコンポーネントの呼び出し

<div>
  <NewsIndex/>
</div>

これで URL「https://YOUR/SERVER/PATH/api/news/」が返す json (中身はコレクション)の id と name を一覧で表示します。

● SWRの自動再検証(自動再読込)について

デフォルトでは自動的に revalidate(再読込)処理が入っています。

「ページがフォーカスした時」 「タブを切り替えた時」 「設定したポーリング間隔」で再読み込みされます。

100msecとフォーカス時に自動再読込

  const options = {
    revalidateOnFocus,
    refreshInterval: 100,
  };
  const { data, error, mutate } = useSWR(url, fetcher, options);
revalidateIfStale = true: automatic revalidation on mount even if there is stale data (details)
revalidateOnMount: enable or disable automatic revalidation when component is mounted
revalidateOnFocus = true: automatically revalidate when window gets focused (details)
revalidateOnReconnect = true: automatically revalidate when the browser regains a network

公式 : https://swr.vercel.app/docs/options
参考 : https://bit.ly/3Aicc4w

● fetch と axios どちらを使用するか?

axios

const options = {
  url: 'http://localhost/test.htm',
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  data: {
    a: 10,
    b: 20
  }
};

axios(options)
  .then(response => {
    console.log(response.status);
  });

fetch

const url = 'http://localhost/test.htm';
const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  body: JSON.stringify({
    a: 10,
    b: 20
  })
};

fetch(url, options)
  .then(response => {
    console.log(response.status);
  });

● データのPOST(送信)


● 参考

zeit製のswrがすごい - Qiita

引用 : https://bit.ly/3DkNoL0

【JS】Fetch API のResponse には気をつけて。axios とは違うぞ。。。 - 7839

No.2062
02/22 22:58

edit