LoginSignup
1
0

More than 1 year has passed since last update.

useSWRで躓いた話

Posted at

そもそもuseSWRとは?

キャッシュからデータを返し、次にフェッチリクエストを送り、最後に最新のデータを持ってくるという処理を行なってくれるもの。APIを通してデータの取得やキャッシュを簡単に記述する手助けをしてくれます。

使い方

npm i swr

でインストールし、ファイルの頭で宣言します。

import React from 'react'
import useSWR from 'swr'

export default function Home() {
  const fetcher = (...args) => fetch(...args).then(res => res.json())
  const { data } = useSWR('/data.json', fetcher)

  return (
    <div>
      <div className="alert alert-primary text-center">
        <h5 className="mb-4">
          {data != undefined ? data.message : 'error...' }
        </h5>
        <table className="table table-dark">
          <thead>
            <tr><th>Name</th><th>Mail</th><th>Age</th></tr>
          </thead>
          <tbody>
            {data != undefined ? data.data.map((value, key)=> (
              <tr key={key}>
                <th>{value.name}</th>
                <td>{value.mail}</td>
                <td>{value.age}</td>
              </tr>
            )) : <tr><th></th><td>no data.</td><td></td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}

上記では外部にdata.jsonというファイル名のものを用意しています。

{
    "message": "This is sample JSON data.",
    "data": [
      {"name":"Kevin", "mail":"kevin@abc", "age":39},
      {"name":"Baba", "mail":"baba@opq", "age":28},
      {"name":"Farmhouse", "mail":"farm@happy", "age":17}
    ]
  }

ここで大事なのは

const fetcher = (...args) => fetch(...args).then(res => res.json())

ネイティブの fetch をラップした fetcher 関数を定義してあげて、 useSWRの第二引数にfetcherを指定してあげることで使用することができます。

最後に

Next.jsの勉強中にuseSWRで躓いてしまったので、記録として残しておこうと思い、今回作成しました。
Next.js,楽しいですね。

1
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
1
0