Having trouble making a table in Vue3 update responsively? Consider using Axios to request updated

My goal is to update a table dynamically using data from a Google Maps query of nearby areas. The query successfully retrieves the correct data in the onMounted lifecycle, but fails to display or return the data during rendering.

I have experimented with making it reactive, using a ref, moving it to a different method, and trying many other strategies.

The axios request does log the relevant data, as indicated in the code below, but for some reason, the axios get value is not returned when rendering.

  <script>
    import { reactive, ref, onMounted } from "vue";
    import Vue3Geolocation from "vue3-geolocation";
    const axios = require("axios");
    export default {
      name: "App",
      setup() {
        let fjson = ref(null);
    
        onMounted(async () => {
          const URL = google query url
          fjson.value = await axios.get(URL, {
            headers: {
              "X-Requested-With": "XMLHttpRequest",
            },
          });
    
          fjson.value = JSON.parse(JSON.stringify(fjson.value));
    
          **** THIS LOGS THE RIGHT VALUE! ****
          console.log(fjson.value.data.results);
    
          if (fjson.value.data.results.length > 2) {
            for (let index = 0; index < 3; index++) {
              console.log(fjson.value.data.results[index]);
            }
          }
    
          **** ALSO WORKS! ****
          fjson.value.data.results.forEach((place) => {
            const lat = place.geometry.location.lat;
            const lng = place.geometry.location.lng;
            let marker = new google.maps.Marker({
              position: new google.maps.LatLng(lat, lng),
              map: map,
            });
    
            google.maps.event.addListener(marker, "click", () => {
              infowindow.setContent(
                `<div class="ui header">${place.name}</div><p>${place.vicinity}</p>`
              );
              infowindow.open(map, marker);
            });
          });
        });
    
        **** LOGS NULL :( ****
        console.log(fjson.value);
        return { mapDiv, coords, fjson: fjson.value };
      },
    };
    </script>
    
    <template>
      <div class="row">
        <div class="col-lg-8 col-md-8 col-sm-12 d-flex align-items-stretch">
          <div class="card" style="width: 100%">
            <div class="card-header text-white" style="background-color: #00aa9e">
              <div v-for="result in fjson">
                <p>{{ result }}</p>
              </div>
              Nearby churches
            </div>
          </div>
        </div>
      </div>
    
      <div ref="mapDiv" style="width: 100%; height: 80vh" />
    </template>

Answer №1

onMounted() does not get triggered within the setup() function; instead, it sets up a callback for when the component is mounted. The setup() function will execute and complete before the onMounted() callback is activated. Since console.log(fjson.value); is placed at the end of the setup() function, it will be executed before any code in the onMounted() function runs, resulting in a null value – this behavior is expected and not an error. The flow typically follows:

  1. setup() is called
  2. fjson is initialized
  3. The onMounted callback is prepared
  4. Logging of fjson
  5. setup() completes
  6. onMounted is invoked and fjson is assigned a value

In addition to these points, there are two other matters to address.

Firstly, your return statement should be structured as follows:

return { mapDiv, coords, fjson };

It's crucial to ensure that you return the reactive object. Simply returning value will provide the value at the time of return (which could be null) and won't reflect updates made by the onMounted callback.

Secondly, your v-for directive should resemble the following:

<div v-for="result in fjson.value.data.results">
   <p>{{ result }}</p>
</div>

Make sure you specify the correct property for v-for just as you would with forEach.

Answer №2

After setting up, onMounted is the function that gets called. If your console.log(fjson.value); is placed outside of your onMounted callback, it will execute before the axios request.

Your v-for loop is incorrect as well. It should look like this:

<div v-for="result in fjson.data.results">
    <p>{{ result }}</p>
</div>

This is because 'results' is the actual array being referenced.

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

Issue with Google charts tooltip displaying literal strings when applied across all fields

this question is quite straightforward. It is inspired by the pie chart example found on the google charts playground Could someone please explain why this code snippet works: function drawVisualization() { // Create and populate the data table. var ...

Creating Your Own Image Hosting Website: Learn how to consistently display an HTML file with a specific image from the URL

I'm currently in the process of developing my own image hosting site at Everything is functioning as intended, but I am looking to make a change. Currently, when a shared image link is opened, it only displays the image. However, I would like it to ...

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

Incorporating one-of-a-kind images into your JavaScript objects

Big shoutout to dmikester1 for sharing a LeaderBoard code that leverages Javascript data to organize players by their points. The current implementation involves using the same image for each player's profile, but I have a vision to customize the pic ...

Significance of v-slot directive with activator bound to the value of "on"

After examining the Vuetify example code for v-toolbar, what exactly does v-slot:activator="{ on }" serve? Consider the following snippet as an example: <template v-slot:activator="{ on }"> <v-toolbar-title v-on="on"> <span>All< ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Angular2: Issue encountered while processing click event

When I click a button on my client application, it sends a request to the server I created using Express. The request handler in the server simply logs 'Delete from server' every time the button is clicked. I am encountering these errors when cl ...

spinning in relation to another object

Currently, I am working on developing a simple Three.js application. One of the main objectives is to synchronize the moon's movements with the Earth's. Although I have a method that allows the moon to rotate in a circular motion statically, the ...

Determining the optimal times to utilize traditional loops instead of array helpers

After writing in Javascript for some time, I've become quite comfortable with using array helpers. However, there have been moments where traditional for loops seem more practical and easier to work with compared to array helpers. Can you provide me w ...

Ways to navigate a div within an iframe that has been loaded

As I load a page(A) inside an iframe, the HTML structure of the embedded content is as follows: <html><body> <div id="div1"></div> <div id="div2"><button>Hello</button></div> </body></html> The ...

An issue with the AngularJS [$parse:syntax] error has been identified when using specific data in the

I encountered an issue when attempting to create an AngularJS ui-grid table with data that includes a '(' and then whitespace before the closing ')' within a string. This resulted in an AngularJS error message: Syntax Error: Token &a ...

Is it possible to simultaneously wait for the completion of two methods instead of awaiting each one individually?

When dealing with 2 async methods, one may want to run them simultaneously but wait for both to finish before proceeding. Here is an example: exports.get = async id => { const part1 = await context.get(id); const part2 = await context.get2(id ...

What is the best way to retrieve the checkbox value using AJAX/jQuery with a Spring form?

My form contains a group of checkboxes identified by the path deliveryStatus, like so: <form:checkbox path="deliveryStatus" value="notDelivered"/> <form:checkbox path="deliveryStatus" value="delivered"/> I came across two helpful examples: E ...

"Utilize the style attribute to modify the appearance based on the

I was the original asker of this question, but I failed to provide a clear description which led to not getting an answer. However, I will now explain everything here. Essentially, I am looking for a JavaScript function that can identify a class with a spe ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

Can a value be concealed within a dropdown list on a form (using PHP or JavaScript)?

Within my form, there is a drop down box listing the 50 states in the U.S. This list is generated using a PHP for loop. Users are required to select their residential state and later on, they must also choose a mailing state if it differs from their resi ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Is it possible to incorporate an expression within NG-MODEL?

Is there a way to bind an expression inside the NG-MODEL directive without causing an error? Can this be achieved using a compile function? Below is my HTML markup: <!DOCTYPE html> <html> <head> <title></title> <l ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...