I’m stuck with a null reference error when trying to pass map boundaries to my API call
I have two versions of my code. One works fine with hardcoded values, but when I try to use dynamic coordinates from Google Maps, I get this error.
Working version with static coordinates:
import fetch from 'node-fetch';
const API_ENDPOINT = "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 fetch(API_ENDPOINT, requestConfig);
const result = await response.json();
return result.data;
} catch (err) {
console.error(err);
}
};
App component (working):
const [mapBounds, setMapBounds] = useState(null);
const [restaurants, setRestaurants] = useState([]);
useEffect(() => {
fetchRestaurantData().then((result) => {
setRestaurants(result);
});
}, []);
Broken version with dynamic parameters:
export const fetchRestaurantData = async (southwest, northeast) => {
try {
const response = await fetch(API_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-key",
},
});
const result = await response.json();
return result.data;
} catch (err) {
console.error(err);
}
};
App component (broken):
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 I made this change. I compared both versions but can’t figure out what’s wrong. Any ideas what might be causing this?