Creating a visual display of multiple markers on a map in React Native

Hey there, I'm a newcomer to react native and I could really use your assistance with something. My issue is that I am trying to display a list of markers on a map where the data is stored in an SQLite database. I am using react-native-maps, so within the MapView component, my code looks like this:

      return (
    <View style={styles.sectionContainer} >
        <TouchableOpacity  onPress={()=>{console.log(arrayData)}} >
          <Text>elements of arrayData</Text>
        </TouchableOpacity>
      <MapView
        style={styles.map}
        mapType='hybrid'
        initialRegion={{
          latitude: 41.73909537455833,
          longitude: 12.701842524111271,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,}}
      >
  
        { arrayData.map((item, index) => (
          <Marker key={index} title={item.name} coordinate={item.coordinates} />
           ))}
      </MapView>
    </View>
  );

The 'arrayData' mentioned above is an array of objects where each object contains 'name' and 'coordinate' information. To populate this array, I initially define an array and then have a function that reads elements from the database and adds them to the array before returning it as 'arrayData'. Here's the relevant portion of my code:

const array = [
    {name: 'a', coordinates: {latitude: 41.73909537455833, longitude: 12.701842524111271,}}
  ]; 

  const location=[
    {latitude: 41.73767484979501, longitude: 12.703637927770613},
    {latitude: 41.738562243639635, longitude: 12.701931037008762},
    {latitude: 41.73870384524446, longitude: 12.700487338006495},
  ];

   const funzione = ()=>{ // get data from database called Users
    try {
      db.transaction((tx) => {
          tx.executeSql(
              "SELECT Title FROM Users", 
              [],
              (tx, results) => {
                  var len = results.rows.length; 
                  if (len > 0) {
                    for(let i=0;i<len;i++){
                      var userTitle = results.rows.item(i).Title;
                      
                      //add the element in the array
                      array.push({name: userTitle, coordinates: location[i]});
                    }
                  }
              }
          )
      });
       return(array);
     } catch (error) {
     console.log(error)
    }  
  } 
  const arrayData = funzione();

My current problem is that when the 'arrayData' is used in the MapView component, only the initial array marker is displayed, even though the console log output shows all the correct elements from the database. It seems like the function is not working as expected. Can anyone provide some guidance or help on this matter? Thank you so much!

Answer №1

It seems like the issue may be due to the asynchronous nature of fetching data from the database while rendering the map. To address this, you can use an useEffect hook to ensure that the request is completed before rendering the Map. Here are a few changes you can make:

1 - Modify your function to be async and await the information retrieval process:

 db.transaction((tx) => {
     **await** tx.executeSql(
          "SELECT Title FROM Users", 
          [],
          (tx, results) => { ...

2 - Instead of using const, create an array with useState hook:

const [array, setArray] = useState([]); 

3 - Utilize the useEffect hook to update the markers list information:

const getData = async () => {
    const response = await funzione();
    setArray(response);
}

useEffect(() => {
    getData ();
}, [])

If you encounter any issues, feel free to reach out to me. Wishing you a wonderful day.

Answer №2

Confirming the accuracy of the initial response, it is important to note that you must also update the sql callback function to generate a fresh set of objects:

(tx, results) => {
  return (results?.rows || []).map((row, i) => ({name: row.item.Title, coordinates: location[i]}));
  }

Subsequently, these new objects should be added to your state array

setArray([...array, ...response]);

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

Ways to notify AngularJS of updates triggered by a Jquery plugin

Currently, I am integrating jQuery timepicker for bootstrap into my project. By utilizing Angular UI-Utils jQuery passthrough, I successfully managed to display the clockface. <input type="text" ui-jq="clockface" ng-model="data.Event.time_end" d ...

Update the three.js geometry when a user modifies the settings using dat.gui

I am currently working on updating a 3D spiral geometry in a canvas as the user adjusts a slider to change the number of coils. My approach involves using the dat.gui plugin for the interface. I have successfully implemented the slider to update an externa ...

Steps to hand off an object from a flatlist to a third-generation descendant?

Having a flatlist of items has been causing some issues for me recently. The problem arises when passing the item to the renderItem component, everything seems to work perfectly fine. However, once that same item is passed to a child component responsible ...

Unexpected behavior found in certain parts of jquery due to the implementation of Ajax

Every time I try to use the ajax code on the same page or an external .js file, it seems to cause issues and prevents other parts of the code (jquery) from functioning properly. The ajax should only trigger when clicking on a specific li element with the c ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Utilizing PostgreSQL for efficient joining operations with character varying arrays

Having recently inherited a PostgreSQL 9.2.4 database, I find myself facing a unique challenge despite my experience with SQL Server. Within this database, there is a table that includes three fields: "age_years", "age_months", and "age_days". The values ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

How to Set up a Shortcut for an NPM Module in Gatsby with the Help of the Root Import Extension

After successfully implementing the gatsby-plugin-root-import plugin to define aliases for my imports in my Gatsby website, I recently attempted to do the same for an npm package. However, despite setting it up correctly as far as I can tell, I keep receiv ...

Using ES6 syntax to inject modules into an extended controller can result in the Unknown provider error

Currently, I am facing an issue with creating a child class ModalCtrlChild extends ModalCtrl from my controller class ModalCtrl. Whenever I attempt to do this, I encounter an unknown provider error related to the modules injected in ModalCtrl. The project ...

Creating a Dynamic Form with Radio Button in Ant Design

I'm currently working on a project that involves creating a dynamic form with radio buttons. I'm facing an issue where I am unable to capture the value of the selected radio button and also struggling to figure out how to only allow one radio but ...

What steps should I take to ensure that the navbar is responsive and mobile-friendly?

After creating a navigation bar in an ejs file, I included it in all the files. The issue is that it looks fine on desktop view but does not respond well on mobile devices. There is some space left on the screen and it's not utilizing the entire width ...

A guide on adding a hyperlink to a table in Node.js using officegen

Currently, I am utilizing a widely-used Node.js library for generating MS Office Word documents. In the officegen module, the code below is used to create a table. When a raw string is provided to the 'val' property inside the table, it generate ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

How can I efficiently multi-map values in React?

In my code, I have an array that links color to a specific value. The input value may come from different properties. const data = { status4Weeks: "2", status8Weeks: "3", status12Weeks: "4" }; Currently, I manually map each property to its correspo ...

Tips for verifying blank form fields

Is there a way to validate empty form fields before submission and show an alert? This validation is important as some fields are hidden using v-show. Here is an example: <!DOCTYPE html> <header> <script src="https://unpkg.com/vue@n ...

Exploring ways to iterate through a Firestore array and retrieve data within a React Native environment

In my Firestore database, I have an array that contains categories of services. I want to display these categories when a user enters the details section. However, I encounter an error whenever I navigate to the Details Screen and attempt to map through t ...

Angular MistakeORAngular Error

Every time I refresh the page, I encounter an error in my code while attempting to display a newly edited and saved text. I've initialized the variable, made the access variable public, but it still doesn't work. Can someone point out what I migh ...

Angular model does not bind properly to Bootstrap 3 DateTimePicker after 'dp.change' event

I am currently implementing the Bootstrap 3 DateTimePicker plugin by eonasdan. While everything seems to be functioning correctly, I have encountered an issue with binding the selected date within the input field to Angular's ng-model. Whenever I make ...

The requests I am sending to expressjs are not being processed asynchronously

const info = require('./randomfolder/info') app.get('/info', info.getInfo) app.listen(3000) // randomfolder/info: exports.getInfo = function(req, res) { setTimeout(function(){ res.send('example') }, 10000) } ...

JavaScript Slider Carousel for React framework

Can anyone assist with this? I need to rewrite everything in a standard algorithm, not as it is currently. I have three elements and I would like to create an infinite loop carousel where the next button takes me back to the first element when I reach the ...