How to make node-fetch to extract a specific parameter only? - javascript

I am trying to extract the priceChange of BNB rather than get the whole detail of the API (https://api.binance.us/api/v3/ticker/24hr?symbol=BNBUSD)
I am using node-fetch model in Node js. The code is:
const fetch = require('node-fetch');
fetch('https://api.binance.us/api/v3/ticker/24hr?symbol=BNBUSD')
.then(res => res.text())
.then(text => console.log(text))

You need to use json method to get the data on node-fetch.
const fetch = require('node-fetch');
fetch('https://api.binance.us/api/v3/ticker/24hr?symbol=BNBUSD')
.then(res => res.json())
.then(instrument => {
console.log(instrument.priceChange)
})

Api that you provided is have json format.It is not a text format.Therefore you need to use
res.json() instead of using res.text().
fetch("https://api.binance.us/api/v3/ticker/24hr?symbol=BNBUSD")
.then((res)=>{
return res.json();
}).then((newdata)=>{
console.log(newdata.askPrice);
})

Related

Why does JavaScript render data from the useEffect() hook but fails to render the data when put in the function body?

I have a JSON file called teams.json that contains the basic structure ("name", "age", "country", "role", "team", and "image") in an object. I'm using React to use the function fetch() to retrieve the data from the local JSON file. When I call the useEffect (shown below) hook, the data is retrieved from the local JSON file and I'm able call a useState function to store the data in a state variable called data.
useEffect() function call
//file path
filePath = "/src/public/teams.json"
const getData = (file) => {
fetch(file)
.then(res => res.json())
.then(data => setData(data))
.catch(err => console.log("Error fetching data", err)
}
useEffect(() => {
getData(filePath)
}, [filePath])
If I try to edit or access data within the useEffect() hook, the data is able to be retrieved without any problems, as such.
.then(data => console.log(data[0]))
This returns a json object that contains the necessary information.
{
"name":"R",
"image":"https://example.com",
"team":"B",
"role":"WB",
"country":"American",
"age":18
}
However, in the main body of my react App, if I try to obtain data from the data state, it gives me an error saying Cannot read properties of undefined, shown below.
Body of React App
return (
<main>
{data[0].country}
</main>
)
But I get this error:
I've tried solutions to previous forums from:
Stack Overflow Discussion Axios
Stack Overflow Discussion Error Axios
I've moved my project to the structure:
-src
--public
*some files*
and put the JSON file in the public folder. It reads it now but still doesn't render. I've also tried using axios but to no avail.
If this is an easy fix, sorry about that! Thanks for your help!
Because the data isn't loaded yet.
Assuming your app is something like
function App() {
const [data, setData] = React.useState();
const getData = (file) => {
fetch(file)
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => console.log("Error fetching data", err));
};
useEffect(() => {
getData(filePath);
}, [filePath]);
return <main>{data[0].country}</main>;
}
you're starting off with an undefined data.
Add a guard against that:
if(!data) return <>Loading...</>;
return <main>{data[0].country}</main>;

I'm getting the first response an empty list

I'm getting data from API like this:
const [software, setSoftware] = useState([]);
const id = match.params.id;
useEffect(() => {
fetch(`http://127.0.0.1:8000/api/software/${id}/`)
.then(response => response.json())
.then(data => {
setSoftware(data)
})
}, [id]);
First response is an empty list, but the next response is my list from API. I tried to use useEffect because setSoftwares is asynchronous, but it didn't help.
So how can I get only my list?
I think you are sending incorrect id for the first time, try to console.log(id) it and check-in the console if id is valid or not.

How to fetch correctly from server side in Node.js

I'd like to fetch/data and serverside fetch.
But I suffered following errors.
response.getCategory is not a function
(()=>{
const url = "/data";
fetch(url)
.then(response => {
console.log("getCategory_main.js",response.getCategory(1));
//displayQuiz(response,1);
});
})();
when we access /data, serverside fetch will be functioned.
const API_KEY="https://opentdb.com/api.php?amount=1&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");
module.exports={
getQuiz:function(res){
fetch(API_KEY)
.then(response => response.json())
.then(json => { const quiz = new Quiz(json);
console.log("getCategory_model",quiz.getCategory(1));
console.log("quiz",quiz);
res.send(quiz);
});
}
};
I can get result
getCategory_model History
I should pass same data from serverside to clientside
but method access succeeded only in serverside..
What is the cause of this ? and how can I fix it ? thanks..
You can't send objects with live methods over the wire as JSON. That is, if your server side Quiz object has a getCategory() method, it won't have one when you send it over to the client.
You'll need to serialize it, e.g.
res.send({
quiz,
categories: [quiz.getCategory(1)],
});
When you fetch data, your'e fetching data (usually as text).
When you create a new quiz with new Quiz(json) your'e reading the json text data and using Quiz to create code from the json text.
So in your first example you should get the text result, and then evaluate the result to json so that you can use getCategory() from Quiz
const url = "/data";
fetch(url)
.then(data => data.json())
.then(json_text=> {
// here you use the text and parse to JSON
const data = JSON.parse(json_text)
// now you can create the Quiz object
const quiz = new Quiz(data)
console.log("getCategory_main.js", quiz.getCategory(1));
});

Fetch recursion using javascript to call Google place API

I need to get a list of results from a Google place API request. The API allows 20 results per page ans I need all results available so I need to go to the next page.The next page is accessible from a token given in the response of the previous request.
I've implemented the code below:
function request(url){
return fetch(url)
.then((response) => response.json())
.catch((error) => console.log(error))
}
This is my recursive function:
export function getListOfActivitiesInACity(city_name,nextPageToken,datas){
const first_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=activity+in+'+city_name+'&key='+ API_TOKEN +'&language=fr'
const next_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken='+nextPageToken+'&key='+ API_TOKEN
var url = nextPageToken ===''? first_url : next_url;
return request(url)
.then((data) => {
const newData = [...datas, data];
if(data["next_page_token"] !== undefined){
return getListOfActivitiesInACity(city_name,data["next_page_token"],newData);
}
return newData;
})
}
And then I call my function and print results
var datas=[];
getListOfActivitiesInACity("Lyon",'',datas)
.then(data => {console.log(data);})
The first iteration of the fetch works fine and gives me the good new url for the next fetch
(I tried it on my broser directy and it works)
But the second fetch return me this :
Object {
"html_attributions": Array [],
"results": Array [],
"status": "INVALID_REQUEST",
}
I really don't understand why it doesn't work , so please can anyone help Thanks

fetch the api data and put it inside the tables

I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}
according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.

Categories

Resources