1

I am new to React Google Maps. I am using this library to create a map with several locations and trying fit the boundaries and center it. I am using it to locate restaurants, hotels and all on that particular location.

This is my code in which i am getting error as well as I am getting TypeError: Cannot read properties of undefined (reading 'lat') console.log(bounds.sw, bounds.ne) == undefined console.log(data) == undefined

App.js

function App(){
    const [places, setPlaces] = useState([]);
      const [coordinates, setCoordinates] = useState({});
      const [bounds, setBounds] = useState({});
    
      useEffect(() => {
        // this use effect for detecting current location
        navigator.geolocation.getCurrentPosition(({ coords:{latitude, longitude} }) => {
          setCoordinates({ lat: latitude, lng: longitude });
          // console.log(latitude,longitude)
        })
      },[]);
    
      useEffect(() => {
        getPlacesData(bounds.sw, bounds.ne)
          // console.log(bounds.sw, bounds.ne)
           .then((data)=>{
            //  console.log(data);
             setPlaces(data)
           })
      },[coordinates, bounds]);
     return(<>
            <Map 
                    setCoordinates={setCoordinates}
                    setBounds = {setBounds}
                    coordinates = {coordinates}
                  />
              <>
              )}

Api.js

import axios from 'axios';

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


export const getPlacesData = async(sw, ne) =>{
    try {
        const {data:{data}} = await axios.get(URL, {
          params: {
            bl_latitude: sw.lat,
            tr_latitude: ne.lat,
            bl_longitude: sw.lng,
            tr_longitude: ne.lng,
          },
          headers: {
            'X-RapidAPI-Host': 'travel-advisor.p.rapidapi.com',
            'X-RapidAPI-Key': 'Key'
          }
        });
        return data;
Gaurav
  • 11
  • 2
  • Effect hooks run when your state is initialised so the first time, `bounds` will be an empty object and `bounds.sw` will be undefined. See the duplicate for how to delay effect hooks until the first update – Phil May 06 '22 at 03:45

0 Answers0