design patterns - Location tracking react component - How to to handle listeners/updates -
i have "dumb" component displays approx. distance between 2 locations.
import react "react" const cos = math.cos const p = math.pi / 180 function getdistance(lat1, lon1, lat2, lon2) { var = 0.5 - c((lat2 - lat1) * p)/2 + c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p))/2 return 12742 * math.asin(math.sqrt(a)) // 2 * r; r = 6371 km } let distance = ({from,to}) => { let distance = getdistance( from.latitude, from.longitude, to.latitude, to.longitude) if (distance < 1.0) { distance = (distance * 100) + "m" } else { distance = distance + "km" } return <span>{distance}</span> } } distance.displayname = "distance"
i want enhance component updating component whenever browsers geo-location changes. created component
class trackingdistance extends react.component { constructor(props) { super(props) this.updateposition = this.updateposition.bind(this) if (trackingdistance.lastposition) { this.updateposition(trackingdistance.lastposition) } else { navigator.geolocation.getcurrentposition(this.updateposition) } } updateposition(position) { this.setstate({from: position.coords}) } componentdidmount() { if (trackingdistance.instances.length === 0) { trackingdistance.watchid = navigator.geolocation.watchposition(position => { trackingdistance.instances.map(instance => instance.updateposition(position)) }) } trackingdistance.instances.push(this) } componentwillunmount() { trackingdistance.instances.remove(this) if (trackingdistance.instances.length === 0) { navigator.geolocation.clearwatch(trackingdistance.watchid) } } render() { return this.state.from ? <distance to={this.props.to} from={this.state.from}/> : null } } trackingdistance.instances = [] trackingdistance.watchid = 0 trackingdistance.lastposition = null
my goal register event listener geo-location updates once in app , not 1 listener every component. worry create circular reference when save component instances in static array trackingdistance.instances
.
also allowed call setstate
method of other components outside component (like in location listener?)
is there other react pattern solve such problem better? can't use mixins, cause using es6 react component classes.
Excellent post, thanks for this. I gathered lots of information from this and I am happy about it. Do share more updates.
ReplyDeleteReactJS Training in Chennai
ReactJS course
ReactJS Certification
Angular Training in Chennai
PHP course in Chennai
Web Designing Training in Chennai
Ethical Hacking Training in Chennai
ReactJS Training in Anna Nagar
ReactJS Training in Velachery
ReactJS Training in Vadapalani