Home > Net >  React.js - Uncaught TypeError: Cannot read properties of undefined (does not happen when data is har
React.js - Uncaught TypeError: Cannot read properties of undefined (does not happen when data is har

Time:09-02

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 onl oad = 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}
          onl oad={map => setMap(map)}
        >
          {offline[0].cameras.map(({ position }) => (
            <Marker
              position={position}
            >
            </Marker>
          ))}
        </GoogleMap>

      </header>
    </div >
  );
}

export default App;

CodePudding user response:

{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)

CodePudding user response:

Please try like this way

offline[0] && offline[0].cameras && offline[0].cameras.map(({ position }) => ( ...

CodePudding user response:

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>
))}
  • Related