1
1

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 1 year has passed since last update.

React – 定期的にバックエンドAPIにリクエストし続ける (例 1秒間隔でsleepする) (リアルタイム更新したい)

Last updated at Posted at 2023-01-04

バックエンドAPI

JSONで現在時刻を返すAPIを用意しておく

{
  "time": "2023-01-04T12:31:56.487Z"
}

React コード例


import {useState, useEffect} from 'react'

const AxiosGet = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('http://localhost:3000/');
      const data = await response.json();
      setData(data);
    }

    const interval = setInterval(() => {
      fetchData();
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return data ? <div>{data["time"]}</div> : <div>Loading...</div>;
}

export default AxiosGet;

動作例

1秒ごとに時刻表記が更新されるのが分かる

image
image

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?