mardi 25 décembre 2018

React service singleton alternative

I'm making a ReactJS application using the google maps library & I'm trying to abstract most map logic to a service, so that I could exchange the google maps library with leaflet if I wanted to in the future.

The way it works now is that I have a component loading the map library and attaching it to a div. The onLoad callback will set the map in this service, so that I can keep a reference to it.

onMapLoad={(map: Map) => {
    mapService.setMap(map);
    props.mapLoaded();
}}

The service also needs to have access to my redux store to dispatch actions when for example a certain marker on the map is selected. I'm setting this while bootstrapping the application in the index.tsx file

const store = getStore();
mapService.setStore(store);

The service itself is a singleton, but I'm wondering if there's a better pattern to use with React or just in general. I'll post a shorter version of the service, with some methods left out for brevity. Does anyone have a pattern advice that might improve this practice?

interface MapService {
    predictPlaces: (query: string) => Observable<AutocompletePrediction[]>;
    addMarkerToMap: (surfspot: Surfspot) => void;
    centerMapAroundSuggestion: (suggestion: Suggestion) => void;
    setMap: (newMap: Map) => void;
}

let predictService: google.maps.places.AutocompleteService;
let geocoder: google.maps.Geocoder;
let map: Map;
let store: Store;
let markers: google.maps.Marker[] = [];

const setMap = (newMap: Map) => {
    map = newMap;
}

const setStore = (store: Store) => {
    store = Store;
}

const centerMapAroundSuggestion = (suggestion: Suggestion) => {
    if (!map) {
        throwGoogleMapsNotLoaded();
    }
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    ... further implementation ...
}

const predictPlaces = (query: string): Observable<AutocompletePrediction[]> => {
    if (!map) {
        return of([]);
    }
    if (!predictService) {
        predictService = new google.maps.places.AutocompleteService();
    }
    ... further implementation ...
}

const addMarkerToMap = (place: Place, onSelect: () => void) => {
    const marker = createMarker(place, onSelect);
    markers.push(marker);
}

const createMarker = (place: Place): Marker => {
    if (!map) {
        throwGoogleMapsNotLoaded();
    }
    const marker = new google.maps.Marker({
        ...options...
    });
    marker.addListener('click', () => {
        createInfoWindow(marker)
        if(!!store) {
            store.dispatch(createMarkerClicked(place))
        }
    });
    ... further implementation ...
}

function throwGoogleMapsNotLoaded() {
    throw new Error('Google maps not loaded');
}

export const mapService: MapService = {
    predictPlaces,
    addMarkerToMap,
    setMap,
    centerMapAroundSuggestion
}

Aucun commentaire:

Enregistrer un commentaire