0
0

キャッシュを利用したデータ取得をSWRで簡単に行う

Posted at

今回のゴール

JsonplaceholderにあるデータをSWRライブラリを用いて取得する。

今回使用するJsonplaceholderのURL

https://jsonplaceholder.typicode.com/posts

公式HP

データ取得のための React Hooks ライブラリ – SWR

実践

下記で使用するHeaderコンポーネントは記述がありますが、本記事の内容とは関係ないので無視で構いません。

公式のデータ取得の欄によると、fetcherという定数を定義します。

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

次にuseSWRをswrから読み込みます。第一引数には取得したいURLを記述、第二引数はfeacherを代入します。そして、公式ページに記述があるように分割代入で、取得したデータを下記のように取得して代入します。

  const { data, error, isLoading } = useSWR(
    'https://jsonplaceholder.typicode.com/posts',
    fetcher
  );

そして、下記の記述をすることで状態に応じた出力をすることができる。ローディングしているときはif文でのisLoadingの部分が表示される。エラーの場合は、if文のErrorの部分が表示される。

const Contact = () => {

  const { data, error, isLoading } = useSWR(
    'https://jsonplaceholder.typicode.com/posts',
    fetcher
  );

console.log(data)

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error...</div>;
  return (
    <div>
      <Header />
    </div>
  );
};

export default Contact;

コンソールで取得したデータが出力されると思います。

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