Vue3 array.filter method may result in an empty array

I am currently experiencing an issue with a filter operation that is causing my array to return empty after deletion. The values seem to be evaluated correctly, but for some reason the allSheep reference is being reassigned to an empty array once the operation is complete. I am perplexed as to why this behavior is occurring. Here is the code snippet from my setup function:

  setup() {
    const allSheep = ref([]);
    const formOpen = ref(false);
    const searchQuery = ref("");
    const searchTag = ref("tag_id");
    const axios = inject("axios");
    axios
      .post(GRAPHQL_API_URL, {
        query: print(ALL_SHEEP),
      })
      .then((response) => {
        allSheep.value = response.data.data.get_all_sheep;
      })
      .catch((err) => console.log(err));

    const filteredSheep = computed(function () {
      const query = searchQuery.value.toLowerCase();
      return searchTag.value === "breed"
        ? allSheep.value.filter((el) => el.breed.breed_name.includes(query))
        : allSheep.value.filter((el) =>
            el[searchTag.value].toLowerCase().includes(query)
          );
    });

    function getSearchQuery(query) {
      searchQuery.value = query;
    }

    function setTag(key) {
      searchTag.value = key === "tag" ? (key = "tag_id") : key;
      searchQuery.value = "";
    }

    function handleOpenForm() {
      formOpen.value = true;
    }
    function updateData(data) {
      allSheep.value = [...allSheep.value, data];
    }

    function deleteSheep(id) {
      allSheep.value = allSheep.value.filter((el) => {
        el.sheep_id !== id;
      });
    }

    return {
      allSheep: filteredSheep,
      getSearchQuery,
      setTag,
      handleOpenForm,
      updateData,
      formOpen,
      searchQuery,
      searchTag,
      deleteSheep,
    };
  },
};
</script>

Answer №1

It was as simple as swapping out curly braces for parentheses:

    function removeCow(id) {
          allCows.value = allCows.value.filter((animal) => (
            animal.cow_id !== id;
          )
         );
        }

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

Ways to set a default value in AngularJS when there is no value to compare in an array

Hello, I'm a newcomer to AngularJS and I have the following code snippet in HTML: // Here, I have another ng-repeat loop where I compare home.home_info_id with avg.home_inof_id <div ng-repeat='home in homeDetailInfo'> <div ng-r ...

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...

Is Vue Facing an Endless Loop Bug?

During my experience with Vue, I came across a scenario that led to an infinite refresh loop. To troubleshoot this issue, I initiated a new vue project (version 2) and crafted the following two simple files. If you remove the comments from {{counter}} in t ...

"Error alert: The specified property 'Iscontains' cannot be read because it is undefined" appears in the script for this video

I am currently utilizing AJAX to interact with my backend code. I retrieve URLs from the database and then render them onto the DOM, displaying videos accordingly. However, I am encountering an issue where Uncaught TypeError: Cannot read property ' ...

CodeIgniter 4 Route Fails to Respond when a Different Value is Provided

I am currently engaged in self-studying Code Igniter 4. My focus is on inserting records irrespective of transactions. I have defined parameters such as Add, Edit and Delete. In the case of 'Add' being the passed value, a new record will be inser ...

Tracking changes to variables made by jQuery within a component

I understand that this approach may not be ideal, but I have regular JavaScript code that is changing a variable within my component. The reason for this is due to dynamic JavaScript (generated from Google Blockly) being executed (through `eval`) within m ...

When using VueJS routing with the same component, the OWL Carousel does not get triggered

Hello I am currently experiencing an issue with VueJS rendering images into a Carousel plugin (OwlCarousel) when loading the same component with different variables. When initially loading the page with images, everything functions correctly and the caro ...

Automatically insert nested object keys and values from jQuery into their respective div elements

Below is a sample object that I am working with: "experience": { "1": { "jobtitle": "job_title", "companyname": "company_name", "companytown": "company_town", "companycountry": "company_country", "summary": "Sum ...

What steps can be taken to ensure the enter button (keyboard) functions correctly in forms on IE8?

The issue I'm facing is specific to Internet Explorer. While in any other browser I can easily submit the form by pressing enter on my keyboard, IE8 requires me to actually click the button. I've spent some time searching for solutions, but so f ...

Troubleshooting the issue of executing a script following the usage of jQuery's .after

My goal is to determine the number of div elements on a page and then insert my ad codes after the second div. It seems like using jQuery's .after method is not effective in this scenario. <script> $(function() { var count = $('.pa ...

Changing the src attribute of an <img> tag using Jquery seems to be unresponsive

Hey everyone, I created a simple slider using JqueryUI. When the value falls within a certain range, I generate an Image URL and then attempt to change the src attribute. I am attempting to modify four images. You can view the jsFiddle here. I believe t ...

Conversion of Element Types in JavaScript

How can I make a button add an input field when clicked, and then turn into another button or element once the input is submitted? <button>add tag</button> <input type="text" name="" placeholder="tag"> $(document).ready(function ...

Is it possible to execute ng-repeat on-click when ng-show evaluates to true?

I am currently facing an issue with my table that populates using ng-repeat. The table contains 100 rows, and clicking on any row reveals a new table (using ng-show) with more detailed product information. However, the performance of my web app is being af ...

Make sure to load the gif image before any other images are loaded from the css

Hey there, I'm attempting to display a GIF image before the actual image loads. I found a great example to accomplish this: Example: Java Script function loadimage(imgsrc, change){ var loadimage = new Image(); loadimage.onload = changesrc(imgsrc, c ...

How to incorporate an editable field into a mat-row within a mat-table using Angular 9

I am currently working on enhancing an Angular screen that allows users to manage data in a table with just one column. While the code I have implemented below successfully displays the data, I have been unable to find any examples of how to make this sing ...

Choose an HTML <select> element and its <option> based on the presence of a specific string within its value

<select id='mySelect'> <option value='FirstOption'> Option 1 </option> <option value='SecondOption'> Option 2 </option> </select> I am attempting to automatically select the second option b ...

Utilize useNavigate() in React to redirect users following form validation and submission, implementing routing alongside a loader and defined action

Recently, I created a demo site that features a form for submitting new user information. The following are the key files: App.jsx: import React from 'react'; import './App.css'; import { RouterProvider, createBrowserRouter } from ...

Substitute form input loading

Question: <input id="id_sf-0-use_incident_energy_guess" name="sf-0-use_incident_energy_guess" onchange="show_hide_guess(this.id);" onload="show_hide_guess(this.id);" type="checkbox"> The issue lies with the onload event not working in input fie ...

Retrieve information from a pop-up modal and showcase it in a table within the main controller

How can we transfer data from a modal to a main controller table and update the table on clicking the generate button in the modal? Currently, I am able to retrieve input text data from the generate button click event but the table is not being updated w ...

Is it possible for me to create a distinct component that can display numerous input fields at once?

Introducing the inputArea component, which collects data from input fields and sends it to the server: export default class InputArea extends React.Component { constructor(props){ super(props); this.state = { draw_number: '', ...