1

My current code makes a GET request to fetch data, and then displays the data as markers on Google Maps. I have ommited some code from the following snippet to make it easier to read, but I can assure you the code I removed is not the cause.

If I map offline, then the markers of the locations show up flawlessly on the map. If I instead change it to points, where I am setting from the call of the route, then I will get the error App.js:66 Uncaught TypeError: Cannot read properties of undefined (reading 'cameras').

How do I fix this?

function App() {
  const [points, setPoints] = useState([]);

  useEffect(() => {
    fetch('/cameras-by-date').then(res => res.json()).then(data => {
      setPoints(data);
    });
  }, []);

  const offline = [
    {
      "cameras": [
        {
          "location": "ANZAC HWY, ASHFORD",
          "position": {
            "lat": -34.9502955,
            "lng": 138.575806
          }
        }
      ],
      "date": "03/09/2022"
    }
  ]

  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: MAPS_API_KEY
  })

  const [map, setMap] = React.useState(null)

  const onLoad = React.useCallback(function callback(map) {
    const bounds = new window.google.maps.LatLngBounds(center);
    map.fitBounds(bounds);
    setMap(map)
  }, [])

  if (!isLoaded) {
    return
  }

  return (
    <div className="App">
      <header className="App-header">
        <GoogleMap
          mapContainerStyle={containerStyle}
          center={center}
          zoom={10}
          options={options}
          onLoad={map => setMap(map)}
        >
          {offline[0].cameras.map(({ position }) => (
            <Marker
              position={position}
            >
            </Marker>
          ))}
        </GoogleMap>

      </header>
    </div >
  );
}

export default App;
0

3 Answers 3

1

Please try like this way

offline[0] && offline[0].cameras && offline[0].cameras.map(({ position }) => ( ...
Sign up to request clarification or add additional context in comments.

Comments

1

{points[0]?.cameras.map(({ position }) => ( worked for me.

Found it in this thread after a little more searching: React JS fetching data (error: Cannot read properties of undefined)

Comments

1

You could maybe try to use optional chaining, because when data is received from server/database, at the start it is undefined. So maybe you could do something like that with your map function:

{points?.[0]?.cameras?.map((point, index) => (
    <Marker
     key={index}
     position={position}
     >
     ....
     </Marker>
))}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.