[프로젝트 셋업] Interval 에 따라 REST API 호출하기

김대니·2023년 1월 24일
0

App.js

import logo from './logo.svg';
import React, {useState, useEffect} from 'react';
import './App.css';
import useInterval from './useInterval';

function App() {
  const [message, setMessage] = useState("");

  const onChangeMsg = () => {
    fetch('/api/v1/sample')
      .then(response => response.json())
      .then(message => {
        setMessage(message);
      });
  };

  useInterval(() => {
    onChangeMsg();
  }, 2000);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <div>
            Now: {message.now}
        </div>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

useInterval.js

import { useEffect, useRef } from 'react';

const useInterval = (callback, delay) => {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

export default useInterval;
profile
?=!, 물음표를 느낌표로

0개의 댓글