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.
// 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;
},
};