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();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
export default useInterval;