I know there are multiple questions concerning this error but i try to find a solution for this specific problem.
In the child component i fetch the users geolocation and return an object when the data arrives.
export default () => {
const [location, setLocation] = useState({
loaded: false,
coordinates: { lat: "", lng: "" },
});
const onSuccess = (location) => {
setLocation({
loaded: true,
coordinates: {
lat: location.coords.latitude,
lng: location.coords.longitude,
},
});
};
const onError = (error) => {
setLocation({
loaded: true,
error: {
code: error.code,
message: error.message,
},
});
};
useEffect(() => {
if (!("geolocation" in navigator)) {
onError({
code: 0,
message: "Geolocation not supported",
});
}
navigator.geolocation
.getCurrentPosition(onSuccess, onError)
}, []);
return location;
};
In my parent component i want to update my state using React hooks
import { LocateUser } from "../components";
export default () => {
const [userPos, setUserPos] = useState({ lat: "", lon: "" });
const location = LocateUser();
if (location.loaded) {
console.log(location.coordinates.lat);
setUserPos({ // this creates the error
lat: location.coordinates.lat,
lon: location.coordinates.lng,
});
}
return (
<React.Fragment>
{ location.loaded ? JSON.stringify(location) : 'No location found' }
</React.Fragment>
);
}
I already tried using useEffect and other workarounds but didn't find a solution to make it work.
The problem is that the the first time Child Component is loaded, the geolocation response is empty, a little later it returns the object with it's data.
What would be the solution to get the response from the Child Component and update the Parent Components state?
Thanks in advance
question from:
https://stackoverflow.com/questions/65599019/react-too-many-rerenders 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…