0

I am making an app using this API. The point I'm stuck with is calling the API. If I give the name of the country, the data of that country comes.

Like, res.data.Turkey.All

I want to get the value with input and bring the data of the country whose name is entered.

I am getting value with searchedCountry. But I can't use this value. My API call does not happen with the value I get. I'm getting Undefined feedback from Console.

Is there a way to make a call with the data received from the input?


<template>
  <div>
    <input
      type="search"
      v-model="searchedCountry"
      placeholder="Search country"
    />
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted} from 'vue';

export default {
  setup() {
    let data = ref([]);
    const search = ref();
    let searchedCountry = ref('');

    onMounted(() => {
      axios.get('https://covid-api.mmediagroup.fr/v1/cases').then((res) => {
        data.value = res.data.Turkey.All;
      });
    });

    return {
      data,
      search,
      searchedCountry,
    };
  },
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

I'm work with Vue.js 3

1 Answer 1

1

There are a few things wrong with your code:

  • Your axios call is only called once, when the component mounts (side note here, if you really want to do something like that, you can do it directly within the setup method)
  • You don't pass the value from searchedCountry to the axios API
  • Use const for refs

I'd use a watch on the searchedCountry; something like this (I don't know the API contract):

<template>
  <div>
    <input
      type="search"
      v-model="searchedCountry"
      placeholder="Search country"
    />
  </div>
</template>

<script>
import axios from 'axios';
import { ref, watch } from 'vue';

export default {
  setup() {
    const searchedCountry = ref('');
    const data = ref([]);

    watch(
        () => searchedCountry,
        (country) => axios.get(`https://covid-api.mmediagroup.fr/v1/cases/${country}`).then((res) => data.value = res.data.Turkey.All);
    );

    return {
      data,
      searchedCountry,
    };
  },
};
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Can we do it using Fetch? I can't use the value I get with data.value outside of method, do you have any information about this? I need to use values like "lat, long" in setup.
https://covid-api.mmediagroup.fr/v1/cases?country=${country} this API url works thank you for your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.