1

i am using this api https://api.covid19api.com/live/country/south-africa to get results for my app. What i need to do is instead of writing the country name, i will use a variable which will contain the country name. I need to pass it in the api url

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch("https://api.covid19api.com/live/country/$countryName")
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

3 Answers 3

3

Solution

My bet would be to use the Javascript string format with magic quotes:

This would lead to

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Sign up to request clarification or add additional context in comments.

Comments

3

You can use a template string to achieve that use backticks ` instead of quotes ".

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

How to use template strings in javascript.

var foo = 'Hello world'


// expected result "my variable foo = Hello world"
console.log(`my variable foo = ${foo}`)

I hope this helps.

Comments

2

You can consider using string literal.

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch(`https://api.covid19api.com/live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {

    }

Or String Concatenation:

var countryName = "south-africa"
const fetchAPI = ()=> {
    return fetch("https://api.covid19api.com/live/country/" + countryName)
    .then((response) => response.json())
    .then((result) => {

    }

Resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

2 Comments

the concatenation worked . string literal did not work
enable chat i will share there

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.