Home > Software engineering >  Search bar for list using vuex
Search bar for list using vuex

Time:10-09

I'm working on a vueJs application in which i have a list of uploaders and a search bar, but after adding vuex the list is not rendered anymore. Following the instruction from this question i wrote:

 <template>
  <div class="consumer container-fluid">
      <input
        class="form-control container mb-3"
        placeholder="Enter an uploader"
        v-model="searchedUploader"
      />
      <ul
        class="list-group"
        v-for="uploader in filtered"
        v-bind:key="uploader.username"
      >
        <li class="list-group-item list-group-item-action">
          <p>
            {{ uploader.nome }}
          </p>
        </li>
      </ul>
    </div>
</template>

<script>

import { mapGetters, mapActions } from "vuex";

export default {
  name: "Home",
  data() {
    return {
      searchedUploader: "",
    };
  },
  computed: {
    ...mapGetters(["consumerUploaders","filteredUploaders"]),
    filtered() {
      return this.filteredUploaders(this.searchedUploader);
    },
  },
  methods: mapActions(["fetchUploaders"]),

  created() {
    this.fetchUploaders();
  },
};
</script>

and my consumer.js is:

const state = {
  uploaders: [],
};

const getters = {
  consumerUploaders: (state) => state.uploaders,
  filteredUploaders: (state) => (target) => {state.uploaders.filter(uploader => 
    uploader.nome.toLowerCase().startsWith(target.toLowerCase()))}
};

but is not working. If i replace v-for="uploader in filtered" with v-for="uploader in consumerUploaders" the list is displayed but of course the search-bar is not filtering it. Any idea? Thanks!

CodePudding user response:

You forgot to return the filtered uploaders in getter method:

const getters = {
  consumerUploaders: (state) => state.uploaders,
  filteredUploaders: (state) => (target) => {
    return state.uploaders.filter((uploader) =>
      uploader.nome.toLowerCase().startsWith(target.toLowerCase())
    );
  }
};
  • Related