0

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='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          maxZoom={20}
        />
        <RenderCircle/>
      </MapContainer>
    </>
  );
}
Bassusour
  • 175
  • 6
  • 14

1 Answers1

-2

To solve it, I made it a react component class, and used its setState() instead of using useState(). This avoided the infinite loop.

Bassusour
  • 175
  • 6
  • 14
  • you have to use useEffect hook – Uladz Kha May 02 '22 at 15:22
  • if you want I can help you to implement it, just let's make a live coding session ? – Uladz Kha May 02 '22 at 15:24
  • Thanks for your offer @UladzKha but the infinite loop also happened with `useEffect`, and my current implementation solved my issue (refactor the component into a class instead of using hooks). Not sure why I get downvoted for explaining what solved my issue. – Bassusour May 05 '22 at 09:04