What is the best way to display the original array when the search input for the title is left blank?

When I enter a todo item title in the search input field and then clear the search input, I expect the initial array of todos to be rendered again. I attempted to accomplish this using an if statement but it did not work - only the previously searched todo item is rendered, not the full list of todos. I am unsure if the if statement is the best approach.

Link to code

// Child component

<template>
      <input
        type="text"
        v-model="search"
        @keypress.enter="searchTask"
        placeholder="search task"
      />
      <button @click="searchTask" class="btn">Search</button>
      <Task v-for="task in tasks" :key="task.id" :task="task" />
</template>

<script>
export default {
  computed: {
    tasks() {
      return this.$store.getters.getTasks;
    },
  },
  mounted() {
    this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
  },
  methods: {
    searchTask() {
      let search = this.search;
      this.$store.commit('searchTask', search);
    },
  },
};
</script>

// Store 

export const state = () => ({
  tasks: [],
});

export const actions = {
  async getTasks(context) {
    const res = await fetch('https://dummyjson.com/todos/user/5');
    if (res.ok) {
      let result = await res.json();
      context.commit('setTasks', result.todos);
    }
    return res.ok;
  },

export const mutations = {
  setTasks(state, data) {
    state.tasks = data;
  },
  searchTask(state, search) {
    if (search) {
      state.tasks = state.tasks.filter((t) => {
        return t.todo.toLowerCase().includes(search.toLowerCase());
      });
    } else if (search === '') {
      return state.tasks;
    }
  },
};

export const getters = {
  getTasks(state) {
    return state.tasks;
  },
};

Answer №1

To maintain the integrity of the original state, it is recommended not to alter it directly. Instead, you can create a getter using the method style access approach :

export const state = () => ({
  tasks: [],
});

export const actions = {
  async getTasks(context) {
    const res = await fetch('https://dummyjson.com/todos/user/5');
    if (res.ok) {
      let result = await res.json();
      context.commit('setTasks', result.todos);
    }
    return res.ok;
  },

export const mutations = {
  setTasks(state, data) {
    state.tasks = data;
  },
};

export const getters = {
  getTasks:(state) => (search) => {
   if (search) {
      return state.tasks.filter((t) => {
        return t.todo.toLowerCase().includes(search.toLowerCase());
      });
    } else if (search === '') {
      return state.tasks;
    }
  }
};

In order to utilize this getter, call it like so :

computed: {
    tasks() {
      return this.$store.getters.getTasks(this.search);
    },
  },

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 you display directions while using the Google Maps app in a React Native application?

I need assistance with rendering directions between two points (current location and a passed location). Currently, I am using Linking to open the Google Maps App. However, when clicking the button passing the (latitude, longitude), I want the map to disp ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

When scrolling back to the top of the page, the data-spy feature does not re-highlight the "Home" anchor

After experimenting with Data-spy to change the active anchor while scrolling, I encountered an issue. Upon scrolling back up to the top of the page from the about section, the "Home" anchor failed to re-activate. How can this be fixed? I attempted to rem ...

The screen is cloaked in a dark veil, rendering it completely inaccessible with no clickable

Utilizing Bootstraps modals, here is my current layout. Within the site's header, there exists a "settings" button that triggers a modal containing various options. These options are not tied to the question at hand. The button responsible for displ ...

Navigate to a specified div using JavaScript

I'm having an issue with my navigation bar not scrolling to the designated div. Despite looking at other examples, I can't seem to find a solution <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> ...

Gatsby causing issues with Material UI v5 server side rendering CSS arrangement

I shared my problem on this GitHub issue too: https://github.com/mui-org/material-ui/issues/25312 Currently, I'm working with the Gatsby example provided in Material UI v5: https://github.com/mui-org/material-ui/tree/next/examples/gatsby After imple ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

Why is it that every time I try to save values, I keep encountering a 405 error?

Recently delving into the world of factories, my main goal is to store the current settings from page load into the database. I aim to update these settings whenever I click somewhere on the page. Unfortunately, I am encountering an error that says POST ht ...

I discovered that the chips' content was in need of updating once I selected the content from the menu

I want to create a chips feature similar to Google Flights where clicking on the chips opens a menu. Currently, when I click on the chips, the menu opens up and 'Sports' is displayed as a chip. However, I want to update the 'Sports' tex ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Issue with accessing property `_meta` in Chartjs and Vue.js

I'm currently in the process of developing an application using Vue.js along with Chartjs. A persistent issue I am facing involves making an http call to a service, fetching data, parsing it, and then passing it into my Chartjs component. The problem ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Transforming timestamps to month day, year format and back again without the use of any NPM packages

I have developed a microservice that converts Unix timestamps to a format like Dec 01, 2017 and vice versa. The microservice is deployed at this link: timestamp I am wondering if there is a better way to achieve this without using third-party NPM modules. ...

Steps for triggering a logout using MSAL2Provider

Currently, I am incorporating the React Login Microsoft-Graph-Toolkit component (shown in the code snippet below) along with MSAL2Provider to facilitate user login functionality in my Active Directory application. Although this setup is functioning smoothl ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

What is the best way to send multiple id values with the same classname as an array to the database via AJAX in Codeigniter?

Hey everyone, I'm facing an issue where I need to send multiple IDs with the same class name but different ID values to the database using AJAX. However, when I try to do this, only the first value is being picked up and not all of them. How can I suc ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Flask Blueprints cannot overwrite the static path

I am attempting to utilize Flask Blueprints for serving a multipage web application. Webapp structure: Landing page html->login->Vuejs SPA Flask structure: app/ client/ dist/ static/ js/ css/ ...