How do I refresh my react app every 2 seconds?
import React, {useState, useEffect} from 'react';
import {Route, Switch, useLocation} from 'react-router-dom';
import Home from './Home';
function App() {
const location = useLocation();
console.log(location);
const [feedbacks, setFeedbacks] = useState([]);
useEffect(() => {
const fetchArticles = async () => {
setFeedbacks([]);
const url = 'https://url.abc.com/';
const api_response = await fetch(url);
let data = await api_response.json();
setFeedbacks(data);
}
fetchArticles();
}, [])
const data = {feedbacks};
return (
<div className="App">
<Switch>
<Route path="/" render={() => <Home data={data}/>} exact/>
<Route path="/:username" render={() => <Home data={data}/>} exact/>
</Switch>
</div>
);
}
export default App;
CodePudding user response:
Have you tried using setInterval();
on fetchArticles
? Something like:
setInterval(fetchArticles(), 2000)
CodePudding user response:
There is a JS function for intervals "setInterval" run the function you pass in a regular interval in ms.
This should work:
const fetchArticles = async () => {
setFeedbacks([]);
const url = 'https://url.abc.com/';
const api_response = await fetch(url);
let data = await api_response.json();
setFeedbacks(data);
}
useEffect(() => {
setInterval(fetchArticles(), 2000)
}, [])
CodePudding user response:
useEffect(() => {
const fetchArticles = async () => {
setFeedbacks([]);
const url = 'https://url.abc.com/';
const api_response = await fetch(url);
let data = await api_response.json();
setFeedbacks(data);
}
setInterval(fetchArticles(), 2000)
}, [])