"Updating values in an array using Vue 3 ref is not working as

Description

Seeking assistance with Vue 3 and the composition API. Struggling to delete values in an array declared with ref.

Code showcase

Sharing my code below:

<script setup lang="ts">
import { IPartnerCategory, IPartners } from '~~/shared/types'

const selectedPartnershipCategories = ref([])
const props = withDefaults(
  defineProps<{
    partnershipCategories?: IPartnerCategory[]
    partnerships?: IPartners[]
    freelancer?: boolean
  }>(),
  {
    partnershipCategories: () => [],
    partnerships: () => [],
    freelancer: false,
  }
)

const emit =
  defineEmits<{
    (e: 'update:value', partnership: IPartnerCategory): void
    (e: 'update:selected', select: boolean): void
  }>()

const updateSelectedPartnership = (partnershipId: string, categorySelected: boolean) => {
  if (categorySelected && !selectedPartnershipCategories.value.includes(partnershipId)) {
    return selectedPartnershipCategories.value.push(partnershipId)
  }
  if (!categorySelected && selectedPartnershipCategories.value.includes(partnershipId)) {
    const clearedArray = selectedPartnershipCategories.value.filter((i) => {
      return i !== partnershipId
    })
    console.log(clearedArray)
  }
}

const select = (event) => {
  updateSelectedPartnership(event.fieldId, event.isSelected)
}
</script>

  • The array is named selectedPartnershipCategories
  • A function called updateSelectedPartnership is invoked whenever a value in the selectedPartnership array is updated
  • Upon logging, the clearedArray logs only pushed values, not deleted ones.

Appreciate any help you can provide :)

Answer №1

The reason for this behavior is that the filter function in JavaScript creates a shallow copy of the original array without modifying it.

const colors = ['blue', 'red', 'green', 'yellow', 'orange'];

const filteredColors = colors.filter(color => color.length > 4);

console.log(filteredColors);
console.log(colors);

If you intend to make changes to the original array such as selectedPartnership, you should consider using methods like splice or reassigning the modified array back to selectedPartnership.

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 verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

"Troubleshooting a callback problem in jQuery involving JavaScript and AJAX

UPDATE3 and FINAL: The problem has been resolved with the help of Evan and meder! UPDATE2: To clarify, I need the existing function updateFilters(a,b) to be called, not created. My apologies for any confusion. The issue with the code below is that udpate ...

Check an image preview prior to uploading through FileReader, rotates the image

After browsing through numerous posts about viewing images before uploading, I stumbled upon an intriguing solution that claimed to be simple using FileReader: function displayImage(input) { if (input.files && input.files[0]) { var reader = ne ...

Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. ...

Whenever I save innerHTML to a text file, a newline break is automatically inserted in the saved text file. The same newline break also appears when I reload the page

Whenever the button is clicked, the text file saves with a line break for every p tag inside div1, not just the first one. <p>x1</p> ....linebreak If the button is clicked three times, reloaded, and then clicked again, the result is as follows ...

Gradually make text disappear while scrolling

On my webpage, I have a background image that remains fixed and centered. When the content on the page is long enough to overflow, I want the text to appear inside the image and fade out as you scroll towards the top or bottom of the image. I do not want a ...

Insert HTML code that is activated when the selection is modified

I have a simple dropdown menu in my HTML code. HTML <select name="breed" onchange="breedChanged()"> <?php while ($row = gdrcd_query($result, 'fetch')){ ?> <option value="<?php echo $row['id_breed']; ?& ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

When incorporating MDX and rehype-highlight on a next.js site to display MD with code snippets, a crash occurs due to Object.hasOwn

I'm encountering an issue with my setup that is based on examples from next.js and next-mdx-remote. Everything was working fine until I added rehypeHighlight to the rehypePlugins array, which resulted in this error. Any thoughts on why this could be h ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

What are the memory-saving benefits of using the .clone() method in Three.js?

As I work on my game project, I am including a whopping 100,000 trees, each represented as a merged geometry. Utilizing the tree.clone() method to add them from a cloned model has helped save a significant amount of memory. Unfortunately, the game's p ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

Uploading images with AngularJS and PHP

Despite having successfully done this in the past, I am currently facing an issue and I am completely stumped as to what could be causing it. The problem I am encountering is related to uploading an image using Angularjs and passing it to a PHP file. Stra ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

Design interactive Vue form with customized questions based on user response

I am looking to dynamically create a form with conditional fields. The structure of the form is stored in an object called Q. Below is an example of a Vue component that utilizes bootstrap-vue. <template> <div> <div v-for="q of ...

What is the process for inserting a scroll bar within a div element?

   I have recently created a webpage using some divs, along with a bit of CSS and JavaScript. I am struggling to figure out how to add a scrollbar to one of my divs. The code is not overly complex, as it includes both CSS and JavaScript. <html> & ...

Managing large datasets effectively in NestJS using fast-csv

Currently leveraging NestJS v9, fast-csv v4, and BigQuery for my project. Controller (CSV Upload): @Post('upload') @ApiOperation({ description: 'Upload CSV File' }) @ApiConsumes('multipart/form-data') ... // Code shorten ...

Is the process of converting text to PNG and then reading it as a stream all completed on the front-end?

Is it feasible to achieve the following task? Allow the user to input text Generate a PNG from the entered text Upload the PNG to Pinata, in ReadStream format Perform all of these actions on the front-end Steps (1) and (2) have been successfully complete ...

Is there anybody who can assist me with ${}?

Having an issue with using ${'variable'+i} in a loop function. The goal is to call each function from a loop. Explored template literals but couldn't find a solution for this specific problem. Desired format: ${'variable'+i} // (w ...

How to Use jQuery Slice to Display the Top N Items from a Dropdown Menu

How can I display only the top 10 results from multiple UL lists in my navigation? The code snippet provided below currently works for the first list, but how can I extend this functionality to all of the lists? $(document).ready(function() { var elem ...