The button on my VUE 3 quiz app is not changing to 'Finish' when I reach the final question

Struggling with my Vue 3 quiz app - everything works perfectly until I reach the last question. The button text should change to 'Finish' once the final question is loaded. Despite hours of searching and even using copilot, I still can't find the error. How can I update the button text after reaching the last question in Vue?

<script setup>
import { ref, computed } from 'vue'

const questions = ref([
  {
    question: 'How many books are in the kjva bible?',
    answer: 0,
    options: [
      '80',
      '32',
      '60',
    ],
    selected: null
  },
  {
    question: "What is the name of Israel's first king?",
    answer: 2,
    options: [
      'David',
      'Asa',
      'Saul',
    ],
    selected: null
  },
  {
    question: 'Salvation is of the...?',
    answer: 1,
    options: [
      'Egyptians',
      'Jews',
      'Edomites',
    ],
    selected: null
  }
])

const quizCompleted = ref(false)
const currentQuestion = ref(0)
const score = computed(() => {
  let value = 0
  questions.value.map(q => {
    if(q.selected == q.answer) {
      value++
    }
  })
  return value
})

const getCurrentQuestion = computed(() => {
  let question = questions.value[currentQuestion.value]
  questions.index = question.value
  return question 
})

const setAnswer = evt => {
  questions.value[currentQuestion.value].selected = evt.target.value
  evt.target.value = null
}

const nextQuestion = () => {
  if(currentQuestion.value < questions.value.length -1) {
    currentQuestion.value++
    console.log('currentQuestion.value type:', typeof currentQuestion.va...
    
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Montserrat', sans-serif;
}

body {
  background-color: #271C36;
  color: #fff;
}
</style>


I've attempted to debug by console logging the nextQuestion function without success. I suspect that the issue lies in the button logic but I'm unsure.

Answer №1

getCurrentQuestion retrieves a question without an index property. This means that getCurrentQuestion.index (undefined) will never be equal to questions.length - 1 (2).

The correct comparison should be:

currentQuestion === questions.length - 1
.


A few additional points to consider:

  • I suggest renaming currentQuestion to either currentIndex or currentQuestionIndex
  • Avoid using loose comparison operators like (== and !=)
  • You can skip using setAnswer by utilizing v-model.number
  • You can omit the use of getCurrentQuestion. Instead, you could implement:
<section
    class="quiz"
    v-for="current in [questions[currentQuestion]]"
    :key="current.question"
>
    <!-- utilize `current` -->
</section>

View it in action here

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

How can we optimize ternary statements within ternary statements in Type Script and React Native for best practices?

Can you help me optimize this code snippet that uses nested ternary operators for better readability and correctness? <TouchableOpacity style={ darkMode ? filterState === 'A' ? styles.activeButtonDark : styles.buttonDa ...

Is the webdriver.io waituntil method designed to return a boolean value of true or false

I am working on an automation framework using webdriver.io v5. I need to receive a boolean response from the code snippet below: waitAndCheckForContactToBePresent(contactName) { return browser.waitUntil((value) => { return this.chec ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

Is there a way to verify if the JSON Object array includes the specified value in an array?

I am working with JSON data that contains categories and an array of main categories. categories = [ {catValue:1, catName: 'Arts, crafts, and collectibles'}, {catValue:2, catName: 'Baby'}, {catValue:3, catName: 'Beauty ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

What is the best way to manage variables that are not present in a Vue.js template?

When working with vue.js templates, I often come across instances like this: {{ jobs[0].stages[0].node.name }} If a job has no stages, the entire template fails to load and vue.js admin throws this warning: Error in render: "TypeError: Cannot read prope ...

Error encountered: Multer TypeError - fields does not have a function called forEach

I'm currently working on a metadata reader using multer in node.js with express on c9. I've spent some time searching for solutions to my issue, but it seems like no one else has encountered the error I am facing: TypeError: fields.forEach is no ...

Ways to resolve Error: Project needs yarn, but it is not currently installed

Just finished setting up my new project using the following commands: npm install --global yarn vue create elecprog yarn serve (-> encountered an error) Running everything through VS Code terminal. PS D:\elcp\elecprog> yarn serve yarn run ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Why isn't the page being redirected when attempting to use JavaScript with window.location and window.location.href?

Currently, I have implemented a login system on my website. The process involves triggering an ajax request to a designated PHP script upon the user clicking the submit button. This script is responsible for logging in the user and responding with the mess ...

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

What is the best way to switch between light and dark themes with the ability to locally store the current theme?

Being new to the realm of react, I have been delving into the implementation of new features using Material-UI. One particular feature I am working on involves toggling between light and dark themes, with the current theme being stored locally within the b ...

Can a type alias be created for more than one parameter of a class or function with multiple type parameters?

When using Vue, there are situations where a generic function may require 3, 4, or even 5 type parameters. Is it possible to create a type alias for these parameters in order to avoid typing them out repeatedly? Something like this perhaps: // Example of ...

What is the process for integrating tailwindcss into a vite project?

I have recently started using vite version 0.16.6 and I am looking to transition a vuepress website to utilize vite. The main challenge I am facing is figuring out how to set up tailwindcss with vite. In my CSS file named index.css @tailwind base; @tail ...

Incorporate measurement markers into the graphic (ESRI JavaScript)

Is there a way to add a scale to a single graphic in a graphics layer? I currently have all the graphics shown in the same scale, but I need each graphic to have a different scale. I added the graphics using map.graphics.add() and SimpleSymbol. Any sugge ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

What is the recommended approach for organizing JSON data when dealing with models that have related foreign keys?

Good day! Currently, I am in the process of developing a mono-repo utilizing Laravel and VueJS for CRUD operations on tables with foreign keys. I am facing challenges in establishing a consistent pattern or structure for my JSON. Despite scouring through ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

Error: The function SomeFunction is not recognized as a valid function (Mongoose library)

Help needed! I'm encountering an error stating "TypeError: User.getUserByUsername is not a function at Strategy._verify (.../routes/users.js:65:10) var User = require('../models/user'); passport.use(new LocalStrategy( function(username, ...