I’m running into a problem where I get an error about trying to read property ‘sw’ from null when working with Google Maps and a RapidAPI service.
This version works fine with hardcoded values:
import axios from "axios";
const API_URL = "https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary";
const requestConfig = {
params: {
bl_latitude: "11.847676",
tr_latitude: "12.838442",
bl_longitude: "109.095887",
tr_longitude: "109.149359",
},
headers: {
"x-rapidapi-host": "travel-advisor.p.rapidapi.com",
"x-rapidapi-key": "my-key",
},
};
export const fetchRestaurantData = async () => {
try {
const response = await axios.get(API_URL, requestConfig);
return response.data.data;
} catch (err) {
console.log(err);
}
};
In my component:
const [mapBounds, setMapBounds] = useState(null);
const [restaurants, setRestaurants] = useState([]);
useEffect(() => {
fetchRestaurantData().then((result) => {
setRestaurants(result);
});
}, []);
But when I try to pass dynamic boundary parameters, it breaks:
export const fetchRestaurantData = async (southwest, northeast) => {
try {
const response = await axios.get(API_URL, {
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-key",
},
});
return response.data.data;
} catch (err) {
console.log(err);
}
};
And in the component:
useEffect(() => {
navigator.geolocation.getCurrentPosition(
({ coords: { latitude, longitude } }) => {
setCurrentLocation({ lat: latitude, lng: longitude });
}
);
}, []);
useEffect(() => {
fetchRestaurantData(mapBounds.southwest, mapBounds.northeast).then((result) => {
setRestaurants(result);
});
}, [currentLocation, mapBounds]);
The error happens right after making this change. I think the issue is that mapBounds is null when the effect runs, but I can’t figure out the right way to fix this timing problem.