I have read this post which partly answers my question, but my problem is the infinite loop that the provider.on
method creates with setData(_data)
. I simply want to update the circle information to be rendered from my local blockchain, but the setData(_data)
call creates an infinite loop.
I have tried using a global variable instead of using useState
, which solves the infinite loop, but this updated value cannot be seen in other parts of the code.
function App() {
const initialPos = [55, 12];
const zoomLv = 13;
const [data, setData] = useState([])
const greeterAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3"
const provider = new ethers.providers.JsonRpcProvider("http://localhost:8545");
const contract = new ethers.Contract(greeterAddress, Greeter.abi, provider)
provider.on("block", async (blockNumber) => {
const _data = await contract.getCircle().split(", ") //[lat, lng, radius]
setData(_data)
});
function RenderCircle() {
if (data.length > 1) {
return <Circle center={[parseFloat(data[0]), parseFloat(data[1])]} radius={parseFloat(data[2])} />
}
return null
}
return (
<>
<MapContainer center={initialPos} zoom={zoomLv} id='map'>
<TileLayer
url="https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png"
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
maxZoom={20}
/>
<RenderCircle/>
</MapContainer>
</>
);
}