I am using a custom hook to call the OpenRouteService API and retrieve the safest route from point A to point B. I'm now trying to switch between vehicles (which should give different routes), but the vehicle is not updating in the API call even though the parameter has been updated if I log it. See code below and attached screencaps.
Why is my API call not taking in the updated parameter?
Routehook.js
import { useState, useEffect } from 'react';
import Directions from '../apis/openRouteService';
import _ from 'lodash'
const useRoute = (initialCoordinates, avoidPolygons, vehicle) => {
const [route, setRoute] = useState({route: {}})
const [coordinates, setCoordinates] = useState(initialCoordinates);
const [routeLoading, setRouteLoading] = useState(true);
const [routeError, setRouteError] = useState(false);
useEffect(() => {
const fetchRoute = async () => {
setRouteError(false);
setRouteLoading(true);
try {
// Swap coordinates for openrouteservice
const copy = _.cloneDeep(coordinates)
let startLocation = copy[0];
let endLocation = copy[1];
console.log(vehicle);
// Logs 'cycling-regular' or 'driving-car'
// depending on the parameter when I call the hook
// Call openrouteservice api
const result = await Directions.calculate({
coordinates: [
[startLocation.latLng.lng, startLocation.latLng.lat],
[endLocation.latLng.lng, endLocation.latLng.lat],
],
profile: vehicle,
format: 'geojson',
avoid_polygons: avoidPolygons
})
console.log(result)
// When I check the result the query profile does not contain
// the updated parameter (see screencaps below).
setRoute(result);
} catch (error) {
setRouteError(true);
}
setRouteLoading(false);
}
fetchRoute();
}, [coordinates, avoidPolygons, vehicle]);
return [{ route, routeLoading, routeError }, setCoordinates];
}
export default useRoute;
To give a full overview. In the main component (VanillaMap.js) I have these related snippets:
const [vehicle, setVehicle] = useState('cycling-regular')
const [{ route, routeLoading, routeError }, setCoordinates] = useRoute([startLocation, endLocation], avoidPolygons, vehicle);
const updateVehicle = (state) => {
setVehicle(state);
}
<RouteInfo
route={route}
routeLoading={routeLoading}
routeError={routeError}
vehicle={vehicle}
updateVehicle={updateVehicle}
/>
I then update the vehicle through the updateVehicle function in the RouteInfo.js component.
Solved by creating a new instance of the Directions object each call: