admin管理员组文章数量:1421185
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
3 Answers
Reset to default 3Solution
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
本文标签:
版权声明:本文标题:reactjs - How to pass variable as a parameter in api call fetch in javascript, react native - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744758085a2623583.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论