Assign a variable within a Vue composition file

I'm diving into the world of composition API in Vue and I'm uncertain if my approach is breaking any established patterns.

I have a desire to initialize a variable directly within the composition file:

GameLogic.ts

export default function () {
  ...
    
  const buildMovieGuessed = (movie: Movie, score: number) => ({ ...movie, score });

  const addNewMovieGuessing = (movie: Movie, score: number) => {
    // The moviesGuessed variable isn't being set. It remains an empty array in my template
    moviesGuessed = [buildMovieGuessed(movie, score), ...moviesGuessed];

    currentStep.value += 1;
  };

  return {
    originalMovies,
    activeTerm,
    currentStep,
    activeMovie,
    guessingScore,
    moviesGuessed,
    addNewMovieGuessing,
  };
}

Within the Vue component, I make the following call:

GuessMovie.vue

<script lang="ts">
import { defineComponent } from '@vue/composition-api';
import GameLogic from '@/services/composition/game/GameLogic';
import { ValidationObserver } from 'vee-validate';
import BInputWithValidation from '@/components/_buefy/BInputWithValidation.vue';

export default defineComponent({
  components: {
    ValidationObserver,
    BInputWithValidation,
  },
  setup() {
    const {
      originalMovies,
      activeTerm,
      currentStep,
      activeMovie,
      guessingScore,
      moviesGuessed,
      addNewMovieGuessing,
    } = GameLogic();

    return {
      originalMovies,
      activeTerm,
      currentStep,
      activeMovie,
      guessingScore,
      moviesGuessed,
      addNewMovieGuessing,
    };
  },
  methods: {
    onAddNewMovieGuessingClick() {
      // Triggering the action from this point  
      this.addNewMovieGuessing(this.activeMovie.value, this.guessingScore.value);
    },
  },
  created() {
    // @todo: handle the case where there are no movies present
  },
});
</script>

Is there a way for me to properly initialize the moviesGuessed variable from within GameLogic.ts so that the logic remains centralized?

Answer №1

When you use the addNewMovieGuessing() function to reassign the value of moviesGuessed, you are actually losing the reference to its original value.

If your intention is to add a new movie guess to the beginning of the moviesGuessed array, you can achieve this without losing reactivity by utilizing the Array.prototype.unshift() method:

// BEFORE:
moviesGuessed = [buildMovieGuessed(movie, score), ...moviesGuessed];

// AFTER:
moviesGuessed.unshift(buildMovieGuessed(movie, score));

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

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

Redirecting JavaScript form to search engine

I am struggling with creating a form that enables a user to input text and then directs them to a specified search engine with the input as the query. I am encountering difficulties in getting the JavaScript to properly redirect. An interesting observatio ...

Divide the pair of arrays that are transmitted via JSON

I combined two arrays and passed them through JSON, as shown below: $result = array_merge($json, $json1); echo json_encode($result); Now, to retrieve the data, I am using the following code: $.getJSON('./tarefasaad52', function (data) { } How ...

The combination of Next.JS and React Objects is not acceptable as a React child

Summary: Encountering the error Error: Objects are not valid as a React child (found: [object Promise]) while making a fetch request in a Typescript project. Interestingly, the same code snippet works without errors in a Javascript project. Recently, I ...

The user keeps finding themselves redirected back to the Home page rather than the page they are trying

Within my Angular application, users are authenticated through an OIDC provider using the library angular-auth-oidc-client. In the scenario where a user is not authenticated or their session has expired and they attempt to access a page such as https://loc ...

Is AngularJS the right choice for creating components?

Currently, I am developing a PHP web application with approximately 200 unique views. Most of these views simply display tables or forms. However, there are about 10 pages where users could benefit from dynamic/async components to prevent constant page re ...

Tips for obtaining a subset of `keyof T` where the value, T[K], refers to callable functions in Typescript

Is there a way to filter keyof T based on the type of T[keyof T]? This is how it should function: type KeyOfType<T, U> = ... KeyOfType<{a: 1, b: '', c: 0, d: () => 1}, number> === 'a' | 'c' KeyOfType<{a: ...

Enhancing DataTable Performance with Django Filters

I have implemented a feature where users can apply filters to customize the data displayed in a Table. When a user interacts with these filters, an asynchronous Ajax call is triggered: $.ajax({ url: '/fund_monitor/fund_directory&a ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Differences between ES6 class static method and regular function

When working with NodeJS, I am planning to create some utility functions. I have two options in mind. The first option involves using the traditional approach: module.exports = { random: () => Math.random(), }; Alternatively, I could use an ES6 c ...

Error: 'Target is not found' during React Joyride setup

I am attempting to utilize React Joyride on a webpage that includes a modal. The modal is supposed to appear during step 3, with step 4 displaying inside the modal. However, I am encountering an issue where I receive a warning message stating "Target not m ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

Developing a custom styling class using JavaScript

Looking to create a custom style class within JavaScript tags. The class would look something like this: #file-ok { background-image: url(<?php echo json.get('filename'); ?>); } Essentially, the value returned from the PHP file (json ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Issue with PLUploader in ASP.Net/JQuery: "Add Files" button not functioning post image upload操作

Hello, I've been utilizing the PLUploader controller for ASP.NET in C#. Initially, it works as intended, but after uploading files, the "add files" button becomes disabled or stops working, preventing me from adding more images. Can anyone offer assi ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

The initial render in a Kanban board seems to be causing issues with the functionality of react-beautiful-dnd

I recently integrated a Kanban board into my Next.js and TypeScript project. While everything seemed to be working fine, I encountered a minor glitch during the initial rendering. Interestingly, when I refreshed the page, the drag and drop functionality st ...

Add additional tags to a Vue component that has already been created

Is it possible to dynamically add markup to existing components without directly editing them? Consider this scenario: <!-- Example of an arbitrary component X --> <template> <div> <!-- I would like to insert a headline here -- ...