The error message "trying to access markers property of undefined in the render function" occurred

I encountered this error while running my react-native component and need assistance.

An error stating "undefined is not an object (evaluating 'this.state.markers.map')" occurred. This error appears in the following locations:

  • c:\projects\myapp\src\components\home\hub.js:87:28
  • ...

Here is the relevant code snippet:

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import MapView from 'react-native-maps';

export default class Hub extends Component {
 constructor(props){
   super(props);
   this.state = {
   region: null,
   markers: null,
  mapStyle:null
 };
}

componentWillMount() {
 navigator.geolocation.getCurrentPosition(
   (position) => {
     console.log(position);
      this.setState({
       region: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      },
      markers: {
        latlng: {
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        },
        title: 'marker test',
        description: 'ta ta ra',
      },
    });
  }, (error) => {
    console.log(error);
    this.setState({
      region: {
        latitude: 21.035080,
        longitude: 105.793627,
        latitudeDelta: 0.01,
        longitudeDelta: 0.01,
      },
      markers: {
        latlng: {
          latitude: 21.035080,
          longitude: 105.793627,
        },
        title: 'marker test',
        description: 'ta ta ra',
      },
    });
  },
);
}


onRegionChange = (region) => {
  this.setState({ region });
 }

render() {

const { region } = this.props;
const { markers } = this.props;
console.log(region);
return (
  <View style ={styles.container}>
    <MapView
      style={styles.map}
      region={this.state.region}
      onRegionChange={this.onRegionChange}

    >
    {this.state.markers.map(marker => (
      <MapView.Marker
        coordinate={marker.latlng}
        title={marker.title}
        description={marker.description}
      />
    ))}
    </MapView>
  </View>
);
}
}

Answer №1

  • Start by initializing the state with markers = [];, not with null. Next,
  • create an array of markers (either in componentDidMount or in useEffect if you're using hooks):

    markers:

    [{
            latlng: {
              latitude: 21.035080,
              longitude: 105.793627,
            },
            title: 'marker test',
            description: 'ta ta ra',
          }],
    

    Add each marker as an individual object, so they can be displayed using the map function.

If your code still isn't working after making modifications and debugging, refer to this example featuring multiple functional markers:

https://github.com/airbnb/react-native-maps/blob/master/example/examples/DefaultMarkers.js

Answer №2

An object can be transformed into an Array by using a marker, ensuring that it is an Array during the initial state instead of null (map function is designed for Arrays).

If you wish to assign null in the initial state, modify the code as shown below:


    {this.state.markers && this.state.markers.map(marker => (
          <MapView.Marker
            coordinate={marker.latlng}
            title={marker.title}
            description={marker.description}
          />
        ))}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to change the input source in Ratchet's chat app to come from a text box on the webpage instead of the console

I followed the guidelines on to create a chat app. However, I now want to input data from a text box instead of using conn.send() in the console. How can I achieve this using php? I was successful in redirecting the sent message to an html element like ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Is there a better option than using public methods when transitioning from class-based to function-based React components?

When working with React components that utilize hooks, they must be function-based rather than class-based. I've encountered a challenge transitioning from calling methods on child components in class-based components to achieving the same functionali ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

The ng-show directive is failing to update properly after changes are made to the scope values

I'm experiencing some issues with the ng-show method. I have set it up like this: Even though the username string length is checked, the ng-show method doesn't seem to hide/show the extra text until after another keystroke. How can I make it upd ...

Iterating through a collection of objects, triggering a promise for each object and recording its completion

I have encountered a challenge where I need to iterate through an array of objects obtained from a promise, and for each object in the array, I must invoke another promise. After all these promises are executed, I want to display "DONE" on the console. Is ...

Switching focus between windows while working with React

My current setup involves using React. Every time I run yarn start, I can begin coding and see the changes in my browser. However, there's a recurring issue where my terminal keeps notifying me about errors in my code every 10 seconds or so. This cons ...

Dynamic row addition in Material Design Lite table causes format to break

Here's the HTML markup for creating a checkbox using material-design-lite: <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox"> <input type="checkbox" id="checkbox" class="mdl-checkbox__input" /> <span c ...

Whenever I include an onClick event to a div element, the entire webpage fails to display

Currently taking on the task of developing a seat booking website. I am encountering an issue with adding an event listener to a particular div element, which should trigger a function to store the value of the div. However, upon implementing the onClick e ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

Dynamic data binding in AngularJS with dynamically generated views

The scenario: Currently, I am constructing a wizard in AngularJS that contains tabbed content with each tab representing a step in the wizard. These steps are fetched from the database through a Laravel controller and displayed using ng-repeat. Each tab c ...

When loading a page with Puppeteer using the setContent method, images may not be loaded

Currently, I am experiencing an issue with Puppeteer where it does not load resources that are specified with relative paths (such as background.png in the image src or in CSS url()). When I try to load the content of a local file using setContent(), the o ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Is there a technique I could use to create a visual effect like zooming, but without altering the dimensions of the image?

I'm currently working on a project to develop a photo gallery. let img = document.createElement('img') img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Wikipedia_logo_%28svg%29.svg/1250px-Wikipedia_logo_%28svg% ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...