Navigating the reactive array in Vue 3 with finesse

Currently, I'm facing some challenges with my Vue 3 app in terms of getting things to work as expected.

The main issue lies in properly accessing a reactive array. Let me provide you with the code for better comprehension:

Within my global store store/questions/index.js, I have the following code snippet:


const useQuestionsAndAnswers = () => {
    const data = reactive([])
    const getQuestionsAndAnswers = async () => {
      const response = await fetch('../../../db/questions.json')
      const fetchedData = await response.json();
      if(response.status === 200) {
        fetchedData.data.forEach(obj => data.push(obj))
        console.log(data[0]);  <--------- // The console.log here works fine
      } else {
        console.log('Something went wrong')
      }
    };
      
    onMounted(() => {
        getQuestionsAndAnswers();
    });

    return { data }
}

export default useQuestionsAndAnswers;

Upon running console.log(data[0]), I am able to retrieve the desired object. Therefore, it seems like this part is functioning correctly.

My objective is to utilize this data within a Vue component. Here lies the implementation of the component:

components/calculator/Questions.vue
:

<template>
  <div class="block max-w-4xl" v-if='data'>
    <h3 class='py-4'>Select the option that best describes you</h3>
    {{ data[0] }} // Equivalent to the previous console.log statement.
  </div>
</template>

<script>
import useQuestionsAndAnswers from '../../store/questions/index.js'
export default {
  setup() {
    const  { data }  = useQuestionsAndAnswers();

    console.log(data)

    return {
      data,
    }
  }
}
</script>

However, issues arose at this stage. While displaying the {{ data[0] }} bindings in the DOM functions as intended, attempting to access the question key with data[0].question results in displaying the data correctly initially but becomes undefined upon page refresh. It appears that reactivity might be missing.

An additional complication occurs within the setup() function. Although console.log(data) returns the anticipated Proxy containing my array, trying to access an object within the mentioned array using console.log(data[0]) once again produces undefined.

To illustrate, I will provide an example of the JSON data I am receiving:

{
    "data": [
        {
            "question" : "You are amidst a worldwide pandemic and decide to nationalize a well-known food company (its name starts with V for Vicentín) that has not paid its creditors for years. How would you handle Clarín's criticism?",
            "image": "@/assets/alberto.png",
            "id": 1,
            "answers": [
                {
                    "id": 1,
                    "answer": "I would act tough for a few days and then step back.",
                    "points": 2,
                    "slug": "act-tough"
                }
            ]
        }
    ]
}

In essence, what I aim for is seamless access to the array elements and the ability to display the desired information accurately.

Thank you for your help!

Answer №1

If you're facing a similar issue, I would like to share that the solution was surprisingly simple:

When using v-if='data', I mistakenly believed I was checking if the array actually existed. However, in Vue 3, objects are handled with Proxy, so I was actually checking for the existence of that object.

The solution turned out to be adding length to my condition: v-if='data.length > 0' solved the entire problem. The same technique can be applied within my setup() function when manipulating arrays within the <script>.

And that's all there is to it.

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

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Issue with URL parameter in React when using React Router

Initially, everything was running smoothly in my React project using react-router-dom. However, once I added another Route like so: <Route path="/edit/:id" component={EditPage}/> and tried changing the URL in the browser to http://localhos ...

managing websocket connections across various instances

Looking to grasp the concept of managing websockets across multiple instances in order for it to be accessible by all instances. For example, with three nodes running connected through a load balancer, data needs to be emitted on a specific socket. My init ...

Updating files in a Next.js project and automatically refreshing the page without the need to rerun 'npm run'

For a while now, I've been developing websites using a traditional LAMP stack with javascript (including jQuery) for the frontend. Recently, I decided to explore using javascript for the backend as well and started learning next.js. In the older meth ...

Please ensure the previous v-dialog is closed before opening the next v-dialog

, I've been experimenting with a new vuetify project and have successfully added sign in and signup functionality using v-dialog. The issue I'm facing is that when I call these v-dialogs from multiple components, the previous dialog does not auto ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

Create essential CSS for every .html page using Gulp

Recently, I came across a useful npm package recommended by Google for generating critical CSS: var critical = require('critical'); gulp.task('critical', function (cb) { critical.generate({ base: 'app/', ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Implementing JavaScript to Take an Array of Integers from an HTML Input Field and Sort It

Task: Retrieve 10 Array Values from HTML Input Field and Arrange Them in Ascending Order In order to add 10 values from an HTML input field to a JavaScript array, I have created an input field through which data is passed to the array in JS. Two labels ar ...

Is there a way to deactivate the minutes input feature in the Angular UI Timepicker?

I am using a plugin that displays the time in hours and minutes. However, I only need to show the hours. Is there a way to hide the minutes block? This is my HTML code: <uib-timepicker ng-model="mytime" ng-change="changed()" hour-step="1" minute-step ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

UPPAAL: Choosing an element from a pre-defined array of integers

Currently, I am familiar with how selections operate in UPPAAL. For example, you can utilize a statement such as i : int[2,42] to select all numbers between 2 and 42. Now, I am dealing with a network of n automata (each possessing a unique id) and a two-d ...

Utilizing JavaScript to Load and Showcase Images from a Temporary Image to imgsrc

How can I dynamically display images from the temporary image array 'tempimages' onto the 'img' element with the 'src' property? I have written a code that attempts to display temporary images from 'tempimages[]' on ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Exploring methods to verify a service subscription to a topic provided by a different service

My services provide the following functionalities: @Injectable({ providedIn: 'root' }) export class Service1 { dataHasChanged = new Subject(); private data1; private data2; constructor() {} getData() { return { data1: th ...

Tips on showcasing array elements within a table's tbody section and including several values within the same array

I am struggling to figure out how to display array values in my table rows that I receive from input values. I have created an array, but I can't seem to find a way to display them in the table. Furthermore, I want to be able to add more values to th ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...