I’m struggling with a TypeError when trying to use Google Maps API alongside RapidAPI. The error says it can’t read properties of null, specifically ‘sw’.
Here’s a simplified version of my code that’s causing trouble:
// API.js
const fetchLocationData = async (southWest, northEast) => {
try {
const response = await axios.get('https://example-api.com/locations', {
params: {
minLat: southWest.lat,
minLng: southWest.lng,
maxLat: northEast.lat,
maxLng: northEast.lng
},
headers: { 'API-Key': 'my-secret-key' }
});
return response.data;
} catch (err) {
console.error(err);
}
};
// App.js
useEffect(() => {
fetchLocationData(boundaryBox.southWest, boundaryBox.northEast)
.then(data => updateLocations(data));
}, [boundaryBox]);
The code worked fine with hardcoded coordinates, but breaks when I try to use dynamic values. I’ve double-checked my git diff, but can’t spot the issue. Any ideas on what might be causing this null property access problem?
I’ve encountered similar issues before when working with Google Maps API. One thing that helped me was ensuring the map was fully loaded before trying to access boundary values. You might want to consider adding a listener for the ‘idle’ event on your map instance.
Something like this could work:
google.maps.event.addListenerOnce(map, 'idle', function() {
const bounds = map.getBounds();
const boundaryBox = {
southWest: bounds.getSouthWest(),
northEast: bounds.getNorthEast()
};
fetchLocationData(boundaryBox.southWest, boundaryBox.northEast)
.then(data => updateLocations(data));
});
This ensures that the map has finished loading and the boundary values are available before you try to use them. It solved my null property access issues when I implemented it in a similar scenario.
hey there! sounds like ur boundaryBox might be undefined when the effect runs. try adding a check before calling fetchLocationData:
if (boundaryBox && boundaryBox.southWest && boundaryBox.northEast) {
fetchLocationData(boundaryBox.southWest, boundaryBox.northEast)
.then(data => updateLocations(data));
}
this should prevent the error. hope it helps!
Have you considered using optional chaining in your code? It’s a handy feature that can help prevent these null property access errors. You could modify your fetchLocationData function like this:
const fetchLocationData = async (southWest, northEast) => {
try {
const response = await axios.get('https://example-api.com/locations', {
params: {
minLat: southWest?.lat,
minLng: southWest?.lng,
maxLat: northEast?.lat,
maxLng: northEast?.lng
},
headers: { 'API-Key': 'my-secret-key' }
});
return response.data;
} catch (err) {
console.error(err);
}
};
This way, if southWest or northEast are null or undefined, it won’t throw an error. Instead, it’ll just pass undefined for those parameters. You might also want to add some error handling or default values in case these are undefined.