React/JS newbie here.
I've got a simple react app with the page fetching a number from ItemCounter
API-Gateway. The code works right now and it's able to fetch a value from the lambda/apig url.
import React, { useState, useEffect } from "react";
const Stats = () => {
const [ItemsSupplied, setItemsSupplied] = useState(0);
useEffect(async () => {
signIn();
}, []);
async function signIn() {
// Async Signin functions and calls, followed by getData() call
getData();
}
async function getData() {
let url = "https://re1szvliqk.execute-api.us-east-2.amazonaws.com/ItemCounter";
const response = await fetch(url);
const number = await response.json();
setItemsSupplied(number);
}
return (
<div>
<span> Items Supplied: {ItemsSupplied} </span>
</div>
);
};
export default Stats;
I'm looking for a way to refresh/update this value periodically, let's say every 5 seconds, but couldn't figure it out.
Tried this: Change text every 3 seconds React useEffect, but couldn't merge this with my page and ran into errors. Errors had something to do with the fact that signIn()
and consequently getData()
are already being called in a useEffect()
.
Hoping someone can help me out, Thanks!
CodePudding user response:
You need to add one more useEffect
inside which you need to set an interval for every 5 seconds.
import React, { useState, useEffect } from "react";
const Stats = () => {
const [ItemsSupplied, setItemsSupplied] = useState(0);
useEffect(() => {
signIn();
}, []);
useEffect(() => {
let timer = setInterval(()=>getData(),5000)
return ()=>clearInterval(timer)
},[ItemsSupplied]);
async function signIn() {
// Async Signin functions and calls, followed by getData() call
getData();
}
async function getData() {
let url = "https://re1szvliqk.execute-api.us-east-2.amazonaws.com/ItemCounter";
const response = await fetch(url);
const number = await response.json();
setItemsSupplied(number);
}
return (
<div>
<span> Items Supplied: {ItemsSupplied} </span>
</div>
);
};
export default Stats;