[Vuejs]-Search input using a query using Vuex and Axios

0👍

First thing is that your using v-bind incorrectly, better use v-model:

<input
    class="rounded-l-full w-full py-6 px-6 text-gray-700 leading-tight focus:outline-none"
    id="search"
    type="text"
    placeholder="Search"
    v-model="query"
  />

second thing organize better your code when you are using vuex, I would do it of this way:

Template:

// pass the variable query to the funcion getSearchResults
<button
      class="bg-blue-900 text-white rounded-full p-2 hover:bg-blue-700 focus:outline-none w-12 h-12 flex items-center justify-center"
      @click="getSearchResults(query)"
    >
      <font-awesome-icon :icon="['fas', 'search']" />
    </button>

JS:

// Only import mapActions and mapGetters
// create the variable query inside of data() for v-model
<script>
import { mapActions, mapGetters} from "vuex";

export default {
  name: "Main",
  data() {
    return {
         query:"",
      };
  },
  computed: {
    ...mapGetters(["searchResult"]),
   
    }),
  },
  methods: {
    ...mapActions(["getSearchResults"]),
  },
};
</script>

VUEX:

import axios from "axios";

const state = {
  results: [],
};

const getters = {
  searchResult: (state) => state.results,
};

const actions = {
  async getSearchResults({commit}, query) {
    const res = await axios.get(
      `https://www.theaudiodb.com/api/v1/json/1/search.php?s=${query}`
    );
    // Execute the mutation which receive the data and pass to the state
    commit('returnResults', res.data.artists)
  },
};

const mutations = {
  returnResults: (state, results) => (state.results = results),
};

export default {
  state,
  getters,
  actions,
  mutations,
};

Leave a comment