TypeError: Unable to access properties of null (reading 'sw') while utilizing Google Maps API and RapidAPI

I’m encountering a TypeError while implementing the Google Maps API along with another API from RapidAPI. Here’s a brief overview of my working and problematic code.

Working Code - API → index.js:

import axios from 'axios';

const API_ENDPOINT = 'https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary';

const requestOptions = {
    headers: {
        'x-rapidapi-host': 'travel-advisor.p.rapidapi.com',
        'x-rapidapi-key': 'key',
    },
    params: {
        bl_latitude: '11.847676',
        tr_latitude: '12.838442',
        bl_longitude: '109.095887',
        tr_longitude: '109.149359',
    },
};

export const fetchRestaurantData = async () => {
    try {
        const response = await axios.get(API_ENDPOINT, requestOptions);
        return response.data.data;
    } catch (error) {
        console.error(error);
    }
};

App.js (only relevant parts shown):

const [coordinates, setCoordinates] = useState(null);
const [restaurants, setRestaurants] = useState([]);

useEffect(() => {
    fetchRestaurantData().then((data) => {
        setRestaurants(data);
    });
}, []);

Error-Prone Code - API → index.js:

export const fetchRestaurantData = async (southWest, northEast) => {
    try {
        const response = await axios.get(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': 'key',
            },
        });
        return response.data.data;
    } catch (error) {
        console.error(error);
    }
};

App.js:

useEffect(() => {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude } }) => {
        setCoordinates({ lat: latitude, lng: longitude });
    });
}, []);

useEffect(() => {
    fetchRestaurantData(coordinates.southWest, coordinates.northEast).then((data) => {
        setRestaurants(data);
    });
}, [coordinates]);

After making these adjustments, it results in the given error. I need assistance figuring out what may be wrong in the code. I’ve attempted a thorough review using version control.

Looks like you're facing a TypeError because coordinates starts as null and coordinates.southWest/coordinates.northEast are undefined when fetchRestaurantData is first called. You need a check before accessing them. Here's a quick fix:

useEffect(() => {
    if (coordinates) {
        fetchRestaurantData(coordinates.southWest, coordinates.northEast).then((data) => {
            setRestaurants(data);
        });
    }
}, [coordinates]);

Ensure that you define both southWest and northEast within your state setting logic.