最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to pass variable as a parameter in api call fetch in javascript, react native - Stack Overflow

programmeradmin0浏览0评论

i am using this api 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("/$countryName")
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

i am using this api https://api.covid19api./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./live/country/$countryName")
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)
Share Improve this question asked May 24, 2020 at 18:16 Moeez AtlasMoeez Atlas 1162 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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./live/country/${countryName}`)
    .then((response) => response.json())
    .then((result) => {
      //console.log(result)

Reference

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

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./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.

You can consider using string literal.

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

    }

Or String Concatenation:

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

    }

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论