How to fetch data from api? - javascript

I want to fetch data (particularly market cap)from api and display it inside my div. But my html diplays no data on execution. What could I be doing wrong?
<text id="result"></text>
<script>
// API for get requests
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data.0.market_cap;
})
.catch(error => {
console.log(error);
})
</script>

Two suggestions:
Why not just chain the .then() directly to the fetch()?
You seem to have a bit of confusion on how to access the data in your structure - what you're after is result.data[0].market_cap.
// API for get requests
let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.data[0].market_cap;
})
.catch(error => {
console.log(error);
})
<text id="result"></text>
Aside: you should probably invalidate your API key that you've included here, as it's now out in public and can be used to forge requests as you to this API.

I am using jQuery Framework to do this easily.
Check the code below.
<script>
$.get(
"https://api.lunarcrush.com/v2",
{
data: "assets",
key: "n8dyddsipg5611qg6bst9",
symbol: "AVAX"
},
function (result){
data = JSON.parse(result);
}
);
</script>
You can use jQuery by adding the following code in your <head> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Use result.config.data[0].market_cap; instead of result.config.data.0.market_cap;
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data[0].market_cap;
})
.catch(error => {
console.log(error);
});

You can make it cleaner and simpler:
const fetchData = async(url) => (await fetch(url)).json();
fetchData("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then(res => {
result.innerText = res.data[0].market_cap;
})
.catch(err => {
console.log(err);
});
<text id="result"></text>

Related

Store fetch data in variable to access it later

I'm facing a probably super easy to solve problem regarding fetching.
I'd like to fetch some json datas and store it in a variable to access it later.
The problem is that I always ends up getting undefined in my variable. What's the way to do to deal with that kind of data storing ?
Here's my code.
const fetchCities = () => {
fetch('cities.json')
.then(response => response.json())
.then(data => {
return data;
});
}
let cities = fetchCities();
console.log(cities)
Already looked up for answers but couldn't find a way to do. Thanks !
You could do this very simply with async/await like this:
const fetchCities = async () => {
let cities = await fetch('cities.json');
return cities.json();
};
let cities = await fetchCities();
console.log(cities);
Sending a fetch request takes time, so the console.log works before the data arrives.
The best way to deal with fetch is using async functions and await like so:
const fetchCities = ()=>{
return fetch('cities.json');
}
async function main(){
try {
const res = await fetchCities();
const data = await res.json();
// handle the data here, this will work only after the data arrival
console.log(data);
} catch (err) {
console.log(err);
}
}
main();
Note: await can only be used in async functions, that's the main purpose of the main function.
Or if you want to use .then:
const fetchCities = ()=>{
return fetch('cities.json');
}
function main(){
fetchCities()
.then(res => res.json())
.then(data => {
// handle the data here, all you code should be here
})
.catch (err => console.log(err));
}
main();

Calling React js Fetch Calls In a Sequence

Someone, please help me to call these fetch Api's one after the other as I am using the data which is stored in the backend for my next request. I want them to be called sequentially one complete then next request this way.
Promise.all([
fetch(`http://localhost:5000/zoomapi`,
requestOptions),
fetch('http://localhost:5000/getId')
.then((res) => res.json())
.then((result) => {
this.setState({ zoomid: result });
}),
fetch(`http://localhost:5000/users/zoom?name=${this.state.zoomid}`)
.then((res) => res.json())
.then((result) => {
this.setState({ zoomdata: result });
})
])
.catch((error) => {
this.setState({ error });
});
})
.setState is not a synchronous operation, so you cannot use const id = this.state.zoomid, you can use result instead. In addition, your promises should be chained, not nested. Example:
fetch('http://localhost:5000/getId')
.then((res) => res.json())
.then((result) => {
this.setState({ zoomid: result });
return fetch(`http://localhost:5000/users/zoom?name=${result}`);
})
.then((res) => res.json())
.then((result) => {
this.setState({ zoomdata: result });
})
.catch((error) => {
this.setState({ error });
});

problem when try to fetch data from json file

I have some problems when I try to fetch the data, I didn't get response.
I write the path correctly?
I attached the part of the code and pic of my project hierarchy.
let transportation = [];
const init = () => {
fetch('/data/transportationDataCheck.json')
.then((response) => {
return response.json();
})
.then((data) => {
transportation = data;
}).then(() => {
renderList(transportation);
});
};
try this:
const data = require("../data/transportationDataCheck.json")
console.log(JSON.stringify(data));
Or you may try after changing little URL
let transportation = [];
const init = () => {
fetch('../data/transportationDataCheck.json')
.then((response) => {
return response.json();
})
.then((data) => {
transportation = data;
}).then(() => {
renderList(transportation);
});
};
You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server.
Someone had a similar issue here: Fetch request to local file not working
Depending on what type of file this is, you may not need to make a fetch. You could probably instead require the file:
var transportationDataCheck = require('./data/transportationDataCheck.json');```
Use ./ at the beginning of the path
fetch('./data/transportationDataCheck.json')
.then(response => {
return response.json()
})
.then(data => {
// Work with JSON data here
console.log(data)
})
.catch(err => {
// Do something for an error here
})

its passing as combined values 4,5,6

I am new to promise.
I need to make two different api calls.
from the result of first api call I am getting id in the variable firstAPIid,
https://reqres.in/api/users?page=2
I need to pass this id firstAPIid to the second api call.
but the problem is its passing as combined values 4,5,6 https://jsonplaceholder.typicode.com/comments?postId=4,5,6
from the second api call I need to retrieve email and display it in the browser.
do I need to use promise or async or with redux itself can I achieve it.
I researched and referred the below links but still no luck
https://medium.com/#bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8
can you tell me how to fix it.
providing my code snippet and sandbox below
https://codesandbox.io/s/redux-async-actions-xjdo7
<FetchButton
onFetchClick={() => {
store.dispatch(dispatchFunc => {
dispatchFunc({ type: "FETCH_DATA_START" });
axios
.get("https://reqres.in/api/users?page=2")
// axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log("response.data.data---->", response.data.data);
console.log(
"response.data.data[0].id---->",
response.data.data[0].id
);
dispatchFunc({
type: "RECEIVED_DATA",
payload: response.data.data
});
let firstAPIid = response.data.data.map(obj => {
return obj.id;
});
console.log("firstAPIid---->", firstAPIid);
return new Promise((resolve, reject) => {
//var url = `https://jsonplaceholder.typicode.com/comments?postId=3`;
var url =
`https://jsonplaceholder.typicode.com/comments?postId=` +
firstAPIid;
//response.data.data[0].id;
console.log("second url---->", url);
axios
.get(url)
.then(response => {
var lFilterData = "";
//memberGroupingHelper.filterData(response.data, additionalParams);
resolve(lFilterData);
})
.catch(error => {
if (error.response) {
console.log(
`############## service error from helpeeeeeer reject`
);
}
reject("");
});
});
})
.catch(err => {
dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
});
});
}}
/>
I found your issue. It is happening because you are not processing the result of the promise. To do that just add the .then() and .catch() functions:
<FetchButton
onFetchClick={() => {
store.dispatch(dispatchFunc => {
dispatchFunc({ type: "FETCH_DATA_START" });
axios
.get("https://reqres.in/api/users?page=2")
// axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log("response.data.data---->", response.data.data);
console.log(
"response.data.data[0].id---->",
response.data.data[0].id
);
dispatchFunc({
type: "RECEIVED_DATA",
payload: response.data.data
});
let firstAPIid = response.data.data.map(obj => {
return obj.id;
});
console.log("firstAPIid---->", firstAPIid);
return new Promise((resolve, reject) => {
//var url = `https://jsonplaceholder.typicode.com/comments?postId=3`;
var url =
`https://jsonplaceholder.typicode.com/comments?postId=` +
firstAPIid;
//response.data.data[0].id;
console.log("second url---->", url);
axios
.get(url)
.then(response => {
var lFilterData = "";
//memberGroupingHelper.filterData(response.data, additionalParams);
resolve(lFilterData);
})
.catch(error => {
if (error.response) {
console.log(
`############## service error from helpeeeeeer reject`
);
}
reject("");
});
}).then((previousResponse) => {
//Here you resolved the promise with the resolve value above
console.log(previousResponse)
}).catch((error) => {
//Here you resolved the promise with the reject value above
console.log(error);
});
})
.catch(err => {
dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
});
});
}}
/>
I am not seeing any use of the Promise because what you want to achieve can be done just with axios.
EDIT:
Just with axios you can get it. Modify as below:
<FetchButton
onFetchClick={() => {
store.dispatch(dispatchFunc => {
dispatchFunc({ type: "FETCH_DATA_START" });
axios
.get("https://reqres.in/api/users?page=2")
// axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log("response.data.data---->", response.data.data);
console.log(
"response.data.data[0].id---->",
response.data.data[0].id
);
//First of all we'll create the number of requestes base on the previous Response
const promises = response.data.data.reduce((previousValue, { id }) => {
previousValue.push(axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${id}`));
return previousValue;
},[]);
//We use the built in function to fetch the data
axios.all(promises)
.then((responses) => {
//Here you have all responses processed
const emailsMapped = responses.reduce((previousValue, { data }) => {
const emails = data.map(({ email }) => email)
previousValue.push(...emails);
return previousValue;
}, [])
//You send the emails you want
dispatchFunc({
type: "RECEIVED_DATA",
payload: emailsMapped
});
console.log(emailsMapped);
})
})
.catch(err => {
dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
});
});
}}
/>
Also modifies this line in DataList without the first_name
listItems.push(<div key={fetchedDataId++}>{elem}</div>);

javascript fetch function getting syntax error

i want to fetch json data from openweathermap.org.but whenever i open my console it gives error(syntax error:JSON.parse() like this).and i am unable to find what's wrong with my code.plzz help thanks in advance.
<script>
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json= await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});
</script>
You need to add the link prefix http:///https:// otherwise JS thinks you mean a local file.
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('https://api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json = await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});

Categories