Unhandled promise rejection: TypeError: undefined is not a function evaluating 'departureloc.map' occurs when mapping for setState in react native

12,233

Since departureloc is an Object, therefore you cannot use .map on it

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

If you need to map on Object, use the Object.keys as it returns an array of a given object's properties names and use setState based on the key' properties.

and add a condition not to return undefined values as

Object.keys(departureloc).map(value => {
  if(departureloc[value] && departureloc[value].lat) {
     return //...
  }
}
Share:
12,233
johnobc
Author by

johnobc

Updated on December 04, 2022

Comments

  • johnobc
    johnobc over 1 year

    I am successful on getting through the JSON response from Google Directions as i am trying to get to the transit information from the json response which is initially looks like this when successful.

    Object {
      "geocoded_waypoints": Array [
        Object {
          "geocoder_status": "OK",
          "place_id": "ChIJ2YDFT9zweUgRgt5Tws6n3hs",
          "types": Array [
            "premise",
          ],
        },
        Object {
          "geocoder_status": "OK",
          "place_id": "ChIJW2PCihXxeUgRRWgA9kOzpjY",
          "types": Array [
            "establishment",
            "food",
            "lodging",
            "point_of_interest",
            "restaurant",
          ],
        },
      ],
      "routes": Array [
        Object {
          "bounds": Object {
            "northeast": Object {
              "lat": 52.9242042,
              "lng": -1.466251,
            },
            "southwest": Object {
              "lat": 52.9004767,
              "lng": -1.4801554,
            },
          },
          "copyrights": "Map data ©2018 Google",
          "legs": Array [
            Object {
              "arrival_time": Object {
                "text": "9:21am",
                "time_zone": "Europe/London",
                "value": 1524558107,
              },
              "departure_time": Object {
                "text": "8:56am",
                "time_zone": "Europe/London",
                "value": 1524556589,
              },
              "distance": Object {
                "text": "3.4 km",
                "value": 3407,
              },
              "duration": Object {
                "text": "25 mins",
                "value": 1518,
              },
              "end_address": "Full St, Derby DE1 3AF, UK",
              "end_location": Object {
                "lat": 52.9242042,
                "lng": -1.4756769,
              },
              "start_address": "50 Chatham St, Derby DE23 8TH, UK",
              "start_location": Object {
                "lat": 52.9004767,
                "lng": -1.480144,
              },
              "steps": Array [
                Object {
                  "distance": Object {
                    "text": "0.2 km",
                    "value": 175,
                  },
                  "duration": Object {
                    "text": "2 mins",
                    "value": 123,
                  },
                  "end_location": Object {
                    "lat": 52.900963,
                    "lng": -1.478217,
                  },
                  "html_instructions": "Walk to Randolph Road",
                  "polyline": Object {
                    "points": "_c{aIza`Hm@BEyHC_Ag@S?H",
                  },
                  "start_location": Object {
                    "lat": 52.9004767,
                    "lng": -1.480144,
                  },
                  "steps": Array [
                    Object {
                      "distance": Object {
                        "text": "26 m",
                        "value": 26,
                      },
                      "duration": Object {
                        "text": "1 min",
                        "value": 18,
                      },
                      "end_location": Object {
                        "lat": 52.9007148,
                        "lng": -1.4801554,
                      },
                      "html_instructions": "Head <b>north</b> on <b>Chatham St</b> toward <b>Randolph Rd</b>",
                      "polyline": Object {
                        "points": "_c{aIza`Hm@B",
                      },
                      "start_location": Object {
                        "lat": 52.9004767,
                        "lng": -1.480144,
                      },
                      "travel_mode": "WALKING",
                    },
                    Object {
                      "distance": Object {
                        "text": "0.1 km",
                        "value": 126,
                      },
                      "duration": Object {
                        "text": "1 min",
                        "value": 88,
                      },
                      "end_location": Object {
                        "lat": 52.9007561,
                        "lng": -1.4782714,
                      },
                      "html_instructions": "Turn <b>right</b> onto <b>Randolph Rd</b>",
                      "maneuver": "turn-right",
                      "polyline": Object {
                        "points": "md{aI~a`HEyHC_A",
                      },
                      "start_location": Object {
                        "lat": 52.9007148,
                        "lng": -1.4801554,
                      },
                      "travel_mode": "WALKING",
                    },
                    Object {
                      "distance": Object {
                        "text": "23 m",
                        "value": 23,
                      },
                      "duration": Object {
                        "text": "1 min",
                        "value": 17,
                      },
                      "end_location": Object {
                        "lat": 52.900963,
                        "lng": -1.478217,
                      },
                      "html_instructions": "Turn <b>left</b> onto <b>St Thomas Rd</b><div style=\"font-size:0.9em\">Destination will be on the left</div>",
                      "maneuver": "turn-left",
                      "polyline": Object {
                        "points": "wd{aIdv_Hg@S?H",
                      },
                      "start_location": Object {
                        "lat": 52.9007561,
                        "lng": -1.4782714,
                      },
                      "travel_mode": "WALKING",
                    },
                  ],
                  "travel_mode": "WALKING",
                },
                Object {
                  "distance": Object {
                    "text": "2.5 km",
                    "value": 2460,
                  },
                  "duration": Object {
                    "text": "15 mins",
                    "value": 900,
                  },
                  "end_location": Object {
                    "lat": 52.91829079999999,
                    "lng": -1.4748049,
                  },
                  "html_instructions": "Bus towards Derby",
                  "polyline": Object {
                    "points": "_f{aIzu_HsPw@eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G",
                  },
                  "start_location": Object {
                    "lat": 52.900963,
                    "lng": -1.478217,
                  },
                  "transit_details": Object {
                    "arrival_stop": Object {
                      "location": Object {
                        "lat": 52.91829079999999,
                        "lng": -1.4748049,
                      },
                      "name": "Osmaston Road (Stop A8)",
                    },
                    "arrival_time": Object {
                      "text": "9:13am",
                      "time_zone": "Europe/London",
                      "value": 1524557580,
                    },
                    "departure_stop": Object {
                      "location": Object {
                        "lat": 52.900963,
                        "lng": -1.478217,
                      },
                      "name": "Randolph Road",
                    },
                    "departure_time": Object {
                      "text": "8:58am",
                      "time_zone": "Europe/London",
                      "value": 1524556715,
                    },
                    "headsign": "Derby",
                    "line": Object {
                      "agencies": Array [
                        Object {
                          "name": "Arriva Midlands",
                          "url": "http://www.traveline.info/",
                        },
                      ],
                      "color": "#11416d",
                      "name": "Sapphire 38",
                      "text_color": "#ffffff",
                      "vehicle": Object {
                        "icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
                        "name": "Bus",
                        "type": "BUS",
                      },
                    },
                    "num_stops": 9,
                  },
                  "travel_mode": "TRANSIT",
                },
                Object {
                  "distance": Object { ... truncated from a larger response...
    

    To debug my code my fetch function consists console.log() my attempt on trying to get to the data that i need, i particularly need to get to the departure information and i believe i am successful of doing so, here is my attempt:

    fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + latitude + ',' + longitude + '&destination=' + goingto + '&mode=transit&transit_mode=bus&key=' + apiDirectionskey)
                .then((resdirections) => resdirections.json())
                .then((responseJson4) => {
                    const departureloc = responseJson4.routes[0].legs[0].steps[1];
                    console.log(departureloc);
    

    the code above leads to the following JSON result:

    Object {
      "distance": Object {
        "text": "3.1 km",
        "value": 3129,
      },
      "duration": Object {
        "text": "20 mins",
        "value": 1200,
      },
      "end_location": Object {
        "lat": 52.92222599999999,
        "lng": -1.471283,
      },
      "html_instructions": "Bus towards Derby",
      "polyline": Object {
        "points": "_f{aIzu_HsPw@eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G{AqEJoPcU`A",
      },
      "start_location": Object {
        "lat": 52.900963,
        "lng": -1.478217,
      },
      "transit_details": Object {
        "arrival_stop": Object {
          "location": Object {
            "lat": 52.92222599999999,
            "lng": -1.471283,
          },
          "name": "Bus Station (Bay 19)",
        },
        "arrival_time": Object {
          "text": "9:45am",
          "time_zone": "Europe/London",
          "value": 1524645900,
        },
        "departure_stop": Object {
          "location": Object {
            "lat": 52.900963,
            "lng": -1.478217,
          },
          "name": "Randolph Road",
        },
        "departure_time": Object {
          "text": "9:24am",
          "time_zone": "Europe/London",
          "value": 1524644676,
        },
        "headsign": "Derby",
        "line": Object {
          "agencies": Array [
            Object {
              "name": "Arriva Midlands",
              "url": "http://www.traveline.info/",
            },
          ],
          "color": "#11416d",
          "name": "Sapphire 38",
          "text_color": "#ffffff",
          "vehicle": Object {
            "icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
            "name": "Bus",
            "type": "BUS",
          },
        },
        "num_stops": 12,
      },
      "travel_mode": "TRANSIT",
    }
    

    as it shows it returns the actual JSON information that i need, and i want the transit information particularly the departure_stop location which looks like this:

    "departure_stop": Object {
          "location": Object {
            "lat": 52.900963,
            "lng": -1.478217,
          },
          "name": "Randolph Road",
        }
    

    I am in the process acquiring this data of the departure location so i can setState(). after initial tries of attempting to use .map() so i can aquire at latitude and longitude values, i am failing to get to do so as i am getting this: [Unhandled promise rejection: TypeError: undefined is not a function (evaluating 'departureloc.map')]

    Here is my attempt:

     fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + latitude + ',' + longitude + '&destination=' + goingto + '&mode=transit&transit_mode=bus&key=' + apiDirectionskey)
                .then((resdirections) => resdirections.json())
                .then((responseJson4) => {
                    //const departureloc = responseJson4.routes[0].legs[0].steps[1];
                    const departureloc = responseJson4.routes[0].legs[0].steps[1];
                    console.log(departureloc);
                    let busscoords = departureloc.map((outcome) => {
                        return ( {
                                    latitude: console.log(outcome.departure_stop.location.lat),
                                    //longitude: outcome.departure_stop.location.lng,
    
    
                        });
                    });
                    //this.setState(console.log({ departureloc }));
    
    
                });
        }
    

    Have i missed something? or what is my mistake? Any pointers on how to do this properly would be greatly appreciated. Thanks

    actual JSON from:

     const departureloc = responseJson4.routes[0].legs[0].steps[1];
                        console.log(departureloc);
    
    Object {
      "distance": Object {
        "text": "3.1 km",
        "value": 3129,
      },
      "duration": Object {
        "text": "21 mins",
        "value": 1260,
      },
      "end_location": Object {
        "lat": 52.92222599999999,
        "lng": -1.471283,
      },
      "html_instructions": "Bus towards Derby",
      "polyline": Object {
        "points": "_f{aIzu_HsPw@eHgW_IkOmHcPoLiNgKxQwHvL{LxKuK`G{AqEJoPcU`A",
      },
      "start_location": Object {
        "lat": 52.900963,
        "lng": -1.478217,
      },
      "transit_details": Object {
        "arrival_stop": Object {
          "location": Object {
            "lat": 52.92222599999999,
            "lng": -1.471283,
          },
          "name": "Bus Station (Bay 19)",
        },
        "arrival_time": Object {
          "text": "4:14pm",
          "time_zone": "Europe/London",
          "value": 1524669240,
        },
        "departure_stop": Object {
          "location": Object {
            "lat": 52.900963,
            "lng": -1.478217,
          },
          "name": "Randolph Road",
        },
        "departure_time": Object {
          "text": "3:52pm",
          "time_zone": "Europe/London",
          "value": 1524667961,
        },
        "headsign": "Derby",
        "line": Object {
          "agencies": Array [
            Object {
              "name": "Arriva Midlands",
              "url": "http://www.traveline.info/",
            },
          ],
          "color": "#11416d",
          "name": "Sapphire 38",
          "text_color": "#ffffff",
          "vehicle": Object {
            "icon": "//maps.gstatic.com/mapfiles/transit/iw2/6/bus2.png",
            "name": "Bus",
            "type": "BUS",
          },
        },
        "num_stops": 12,
      },
      "travel_mode": "TRANSIT",
    }
    
  • johnobc
    johnobc about 6 years
    thanks for the reply, im doing you what you are suggesting but still getting the same error here is my attempt: let busscoords = Object.keys(responseJson4.routes[0].legs[0].steps[1]).map((o‌​utcome) => { return ( { latitude: console.log(outcome.departure_stop.location.lat), //longitude: outcome.departure_stop.location.lng, }); }); //this.setState(console.log({ departureloc })); }); }
  • Pritish Vaidya
    Pritish Vaidya about 6 years
    If the object is similar to the second json you've posted, then that should be correct
  • johnobc
    johnobc about 6 years
    i have updated my post above with aditional actual json. here is my updated code let busscoords = Object.keys(responseJson4.routes[0].legs[0].steps[1].departu‌​re_stop.location).ma‌​p((outcome) => { return ({ latitude: console.log(outcome.lat), //longitude: outcome.departure_stop.location.lng, }); but im getting this error: ` [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'responseJson4.routes[0].legs[0].steps[1].departure_stop.loc‌​ation')]`
  • Pritish Vaidya
    Pritish Vaidya about 6 years
    Try this Object.keys(token).map(value => { console.log(token[value].lat) }) where token is your departureloc and check the logs, if it returns the lattitudes
  • johnobc
    johnobc about 6 years
    yes this is the output: 16:46:10 undefined 16:46:10 undefined 16:46:10 52.92222599999999 16:46:10 undefined 16:46:10 undefined 16:46:10 52.900963 16:46:10 undefined 16:46:10 undefined
  • Pritish Vaidya
    Pritish Vaidya about 6 years
    Then if you dont want to return undefined values , you need to add a condition and check for them, whether they are undefined or not
  • johnobc
    johnobc about 6 years
    thats great. i noticed that it printed both latitudes. what if i only want want one of them,departureloc[value].departure_stop.lat puts me back to undefined. [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'Object.keys(departureloc).departure_stop.location')]
  • Pritish Vaidya
    Pritish Vaidya about 6 years
    Object.keys(departureloc) && return you value
  • johnobc
    johnobc about 6 years
    is that within or after the map function if i return? like this? const stopmarkers = Object.keys(departureloc).map(value => (departureloc[value]) => ({ latlng: { latitude: departure_stop.location
  • Pritish Vaidya
    Pritish Vaidya about 6 years
    Within the map function where you return, just add a condition to return only if not undefined
  • johnobc
    johnobc about 6 years
    i have followed your suggestion and my result is this: 00:28:45 Object { "lat": 52.915195, "lng": -1.466357, } 00:28:45 undefined 00:28:45 undefined , here is my latest code const departureloc = responseJson4.routes[0].legs[0].steps[1].transit_details.dep‌​arture_stop.location‌​; console.log(departureloc); const stopmarkers = Object.keys(departureloc).map(value => { if (typeof ((departureloc[value]).lat) !== undefined) { return { latitude: console.log((departureloc[value]).lat)} } else { console.log('null'); }})