0

I'm getting geolocation from the user's browsers that work fine I can display the lon and lat on my screen but as soon as I try to push my data location to a fetch call in my useEffect, I not really what I did wrong...I get the error TypeError: Cannot read property 'photo' of undefined It seems that like the data is not being pushed to the fetch or the lon and lat may be empty in this case .can someone please kindly help

import React, { useEffect, useState } from 'react';
import './App.css';
import Map from './Componets/Map/Map';
import Location from './Componets/Api/Location';
import List from './Componets/List/List';
import Test from './Componets/test/Test';

require('dotenv').config();

const App = () => {
    const [
        Locations,
        setLocations
    ] = useState([]);

    const [
        GoeLocationlng,
        setGoeLocationlng
    ] = useState('');
    const [
        GoeLocationlat,
        setGoeLocationlat
    ] = useState('');

    const [
        Imgdata,
        setImgdata
    ] = useState([]);

    const [
        search,
        setSearch
    ] = useState('');

    const [
        query,
        setQuery
    ] = useState('bar');

    useEffect(
        () => {
            async function example(lon, lat) {
                let response1 = await fetch(
                    `https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=9c348b767f7a0403e907b0788188afba&text=${query}&tags=new&accuracy=+11&media=photos+&geo_context=1&per_page=20&page=1&lat=${parseFloat(
                        lat
                    )}&lon=${parseFloat(lon)}&radius=10&radius_units=km&format=json&nojsoncallback=1`
                );
                let json = await response1.json();

                const promises = json.photos.photo.map((i) =>
                    fetch(
                        `https://www.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=9c348b767f7a0403e907b0788188afba&photo_id=${i.id}&format=json&nojsoncallback=1`
                    )
                );

                const response2 = await Promise.all(promises);

                const json2 = await Promise.all(response2.map((res) => res.json()));

                return {
                    dataset1: json,
                    dataset2: json2
                };
            }
            example(GoeLocationlng, GoeLocationlat)
                .then((i) => {
                    setLocations(i.dataset1.photos.photo);
                    // console.log(i.dataset2.photo);
                    setImgdata(i.dataset2);
                })
                .catch((err) => {
                    console.log(err);
                });
            getLocation();
        },
        [
            query
        ]
    );

    const updateSearch = (event) => {
        setSearch(event.target.value);
    };

    const getSearch = (event) => {
        event.preventDefault();
        setQuery(search);
        // setLocations({});
        setSearch('');
    };

    const getLocation = () => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(getCods);
        } else {
            alert('Geolocation is not supported by this browser.');
        }
    };

    const getCods = (postion) => {
        setGoeLocationlat(postion.coords.latitude);
        setGoeLocationlng(postion.coords.longitude);
    };
    getLocation();

    return (
        <div className="App">
            <Map
                googleMapURL={`https://maps.googleapis.com/maps/api/js?key=AIzaSyA8i9z0T-J6oIs6Rrb7FUqz0rM1jipwrEg&v=3.exp&libraries=geometry,drawing,places`}
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `400px` }} />}
                mapElement={<div style={{ height: `100%` }} />}
                Locations={{ Imgdata }}
            />
            <form onSubmit={getSearch} className="searchForm">
                <input className="search-bar" type="text" onChange={updateSearch} />
                <button className="search-btn" type="submit" value="Search">
                    Search
                </button>
            </form>
            {/* {Locations.map((location) => <Location key={location.id} title={location.title} />)} */}

            {Locations.map((location) => (
                <List
                    key={location.id}
                    title={location.title}
                    farm={location.farm}
                    server={location.server}
                    id={location.id}
                    secret={location.secret}
                />
            ))}

            <h1>{GoeLocationlng}</h1>
        </div>
    );
};
export default App;
  • Can u show me json data (`let json = await response1.json()`) ? – Michael May 19 '20 at 06:06
  • when I console.log(json) I get this error {stat: "fail", code: 999, message: "Not a valid latitude"}code: 999message: "Not a valid latitude"stat: "fail"__proto__: Object but can display the latitude on my screen in a H1 which is longitude 30.895824200000003 latitude -28.530553899999997 – siyanda sokhela May 19 '20 at 06:33

1 Answers1

0

You should check your api again, it's not working correctly. It causes the error TypeError: Cannot read property 'photo' of undefined.

Michael
  • 1,806
  • 2
  • 11
  • 20
  • I think it the way I am trying to pass in the values.....I have looked at the API and used different value it works buts as soon as I try to pass in the value without hard coding them it breaks – siyanda sokhela May 19 '20 at 06:51
  • @siyandasokhela You should call getLocation() in useEffect. After getLocation successfully, call example(GoeLocationlng, GoeLocationlat). In your code, you call getLocation() after example(GoeLocationlng, GoeLocationlat) so GoeLocationlat value is [], it is invalid lat. Moreover, you should initiate GoeLocationlat with a empty string instead of an empty arr [] – Michael May 19 '20 at 07:16
  • I have getLocation() in useEffect at the top then called example(GoeLocationlng, GoeLocationlat) it and updated GoeLocationlat to an empty string...but I'm still getting {stat: "fail", code: 999, message: "Not a valid longitude"} I am I missing something – siyanda sokhela May 19 '20 at 07:50
  • @siyandasokhela Remember that navigator.geolocation.getCurrentPosition() is async func so you have to await it. See this example in this post: https://stackoverflow.com/questions/51843227/how-to-use-async-wait-with-html5-geolocation-api. And pls allow your browser to access your location. – Michael May 19 '20 at 07:59