Issue with null property access in Maps API integration
I’m running into a problem where I get an error about trying to read properties of null, specifically the ‘sw’ property when working with Google Maps and a RapidAPI service.
Working version (hardcoded coordinates):
api/services.js
import axios from 'axios';
const ENDPOINT = 'https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary';
const config = {
params: {
bl_latitude: '10.123456',
tr_latitude: '11.987654',
bl_longitude: '108.555555',
tr_longitude: '109.777777',
},
headers: {
'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',
'x-rapidapi-key': 'my-api-key',
},
};
export const fetchRestaurants = async () => {
try {
const response = await axios.get(ENDPOINT, config);
return response.data.data;
} catch (err) {
console.error(err);
}
};
Main.js
const [mapBounds, setMapBounds] = useState(null);
const [restaurants, setRestaurants] = useState([]);
useEffect(() => {
fetchRestaurants().then((result) => {
setRestaurants(result);
});
}, []);
Broken version (dynamic coordinates):
api/services.js
export const fetchRestaurants = async (southwest, northeast) => {
try {
const response = await axios.get(ENDPOINT, {
params: {
bl_latitude: southwest.lat,
bl_longitude: southwest.lng,
tr_longitude: northeast.lng,
tr_latitude: northeast.lat,
},
headers: {
'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',
'x-rapidapi-key': 'my-api-key',
},
});
return response.data.data;
} catch (err) {
console.error(err);
}
};
Main.js
useEffect(() => {
navigator.geolocation.getCurrentPosition(
({ coords: { latitude, longitude } }) => {
setCoordinates({ lat: latitude, lng: longitude });
}
);
}, []);
useEffect(() => {
fetchRestaurants(mapBounds.sw, mapBounds.ne).then((result) => {
setRestaurants(result);
});
}, [coordinates, mapBounds]);
The error happens right after switching to the dynamic approach. I think the issue is related to timing but I can’t figure out exactly what’s going wrong. Any ideas what might be causing this?