Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a navigation guard as shown below:

beforeRouteEnter (to, from, next) {
  axios.post('api/questions',{
    code: to.params.testcode
  })
  .then(response => {
    next(vm => {
      vm.testData = response.data //load testData object here
    })
  })
}

In addition to displaying the questions, I wanted users to navigate through them using next or previous buttons. So, I created a computed property to handle testData.questions and show one question at a time:

paginatedData () {
  const start = this.pageNumber * this.size,
        end   = start + this.size;
  console.log(this.testData.questions.length)

  // return this.testData.questions.slice(start, end)
}

When checking the length of array using console.log, I noticed an odd behaviour where it initially displayed an error value before showing the actual length. This delay prompted me to experiment with using setTimeout in order to observe the behavior:

paginatedData () {
  const start = this.pageNumber * this.size,
        end   = start + this.size;

  setTimeout(() => {
    console.log(this.testData.questions.length)
  }, 1000);

  // return this.testData.questions.slice(start, end)
}

The updated version now only shows the correct length of the array without any errors being logged.

What could possibly be causing this issue?

Answer №1

The element is prepared and set up before the callback in next() is invoked. Without this preparation, the line vm.testData = response.data would not have any impact. Therefore, the function paginatedData is initially triggered while

this.testData === null || undefined || whatever
, and then, after testData is updated in the callback function of next(), it is triggered again.

To address this issue, you can implement a simple conditional statement like if (!this.testData) return null within the paginatedData method.

Here you can find more information about this topic.

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 is the best way to link and store invoice formset with the main form foreign key in Django?

I am new to Django and need help. I am trying to save my invoice in a database, but the issue I'm facing is that I can't retrieve the foreign key from the main form when I try to save the formset. View.py def createInvoice(request):` if requ ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

Tips for resolving the issue of Vue 3 router with multiple calls to next()

Currently, I am tackling the router functionality of my web application. Each time I use "next" to navigate to a specific section, I encounter an issue where it indicates that I have invoked next() multiple times and warns about potential failures in produ ...

Using jQuery to manipulate XML: Altering XML content using its ID with jQuery

Trying to modify content within an XML using jQuery has been a bit tricky for me. Based on the examples I've found, I believe the code should look something like this: Javascript: get_verrichtingen: function(){ var self = this; var option = ...

Is ajax testing with therubyracer (or execjs) worth trying out?

I'm looking to challenge myself by integrating and testing JavaScript code within a Ruby environment. My main goal is to utilize Ruby to set up the database, interact with it using my JavaScript model, and verify the JavaScript state without resorting ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

A singular Vuejs Pinia store utilizing namespaced actions

Is it possible to separate pinia actions into two distinct namespaces, allowing access through properties n1 and n2 like this: // current store.n1a('hi') store.n2b() // wanted store.n1.a('hi') store.n2.b() // cumbersome workaround: sto ...

A Kendo editor necessitates the use of Kendo JavaScript specifically designed for Angular

Can someone provide guidance on the necessary Kendo libraries for implementing the Kendo editor in AngularJS? The tutorial site suggests that "kendo.all.min.js" is required, but I am hesitant to use it due to its resource-heavy nature. Any assistance wou ...

After applying the cellClass in ng-grid, the row border mysteriously disappears

After applying cellClass to color an entire column, the row border disappears. Here is a link to the Plunker demonstration: http://plnkr.co/edit/4IeQQBTIe8sgHVEBUTAp?p=preview. Does anyone have a solution for this issue? ...

Using the return statement to set a value from a callback function in TypeScript

As I retrieve data from an array of class People, each person has an attendance list represented by Observable<any[]>. // Defining the Person class class Person { id: number; name: string; attendance: Observable<any[]>; // Represents ...

Blur-triggered form validation

Within my webpage, I'm facing an issue with 5 input fields that need to be validated on blur. Instead of relying on alert boxes, I aim to display either an error or success message through DOM scripting. Despite trying various codes, nothing seems to ...

The data display in MUI-Datatable is experiencing an issue where it is unable to read properties of undefined, specifically when trying to split the data

Whenever I include data within the MuiDatatable, it triggers this error: Cannot read properties of undefined (reading 'split') Is there a solution to this problem so that the data can be properly displayed? To demonstrate the issue, I have se ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

Error: react-testing-library throwing validateDOMNesting warning

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>. in tbody (created by TableBody) in TableBody (created by TableBody) in TableBody Inquiry: Is there a way to render the TableBody component within a table ...

Difficulty paginating jqgrid when using an array as the data source

Encountering an issue with pagination in jqgrid while working with array data containing 18 records. Even after specifying pagination:true, pager:jQuery('#pager1'), the records are not displaying in pages. Can anyone assist me in implementing pag ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...