Hi I have been stuck in a React Function useState and geofire. I just want to learn hooks and useState, but I can not have any progress even struggling too much to find a solution. here is my database component code which is throwing an error
import "firebase/database";
import React, { useState } from "react";
const geofire = require("geofire");
const firebaseConfig = {
//my config
};
firebase.initializeApp(firebaseConfig);
// const userKey = "slg3";
const firebaseRef = firebase.database().ref("users/place");
const geoFire = new geofire.GeoFire(firebaseRef);
// geoFire.set(userKey, [26.71, 88.43]).then(
// function () {
// console.log("Provided key has been added to GeoFire");
// },
// function (error) {
// console.log("Error: " + error);
// }
// );
let geoQuery = geoFire.query({
center: [26.71, 88.43],
radius: 0.001,
});
const database = () => {
const [pos, setPos] = useState([]);
geoQuery.on("key_entered", function (key, location, distance) {
setPos((prev) => [...prev, location]);
console.log(
key +
" entered query at " +
location +
" (" +
distance +
" km from center)"
);
});
return (
<div className="location">
{pos.map((item) => {
return <h1>{item}</h1>;
})}
</div>
);
};
export default database;
I am trying to render an h1 everytime a location is returned from geoQuery.on(). I am trying to store locations to state variable but I getting an error as “Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.” I am using geofire for queries. Please help and Thanks.
My query is solved. I have shift this code inside useEffect hook.
Initial code:-
geoQuery.on("key_entered", function (key, location, distance) {
setPos((prev) => [...prev, location]);
console.log(
key +
" entered query at " +
location +
" (" +
distance +
" km from center)"
);
});
Changed code:-
useEffect(() => { geoQuery.on("key_entered", function (key, location, distance) {
setPos((prev) => [...prev, location]);
console.log(
key +
" entered query at " +
location +
" (" +
distance +
" km from center)"
);
});},[]);