How to pass object through GET http param - html

Im trying to send the object Pack through get like:
save_pack(Pack: any){
return new Promise((resolve, reject) =>{
this.http
.get("http://localhost:8000/save_pack?Pack="+Pack)
.subscribe(res => {
resolve(res);
},
(err: any) => {
reject(err);
}
)
});
}
However, when I try to check if the value of that object is correct into my API rest, for example checking it size, I get just an undefined instend of the value of the size of the object.
app.get('/save_pack', async (req,res) => {
console.log(req.query);
const Pack = req.query.Pack;
console.log("Size de Pack en peticion" + Pack.size)
let result = await save_pack(Pack);
res.send(result)
return res;
})
Im I doing something wrong? Im not sure if an object should be send like this.

Related

How to print json api data in reactjs

I'm fetching json api details through GET request and trying to print it. Getting an error:
Error in the console is Uncaught ReferenceError: allUsers is not defined
const Dashboard = ({status, juser}) => {
const [allUsers, setAllUsers] = React.useState([]);
const id = juser.actable_id;
console.log(id); //getting id here as 1
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
console.log(response.data);
setAllUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
React.useEffect(() => {
getAllusers();
}, []);
{allUsers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
}
export default Dashboard;
I'm new to react. Any help is appreciatable.
const [state, setState] = React.useState([]);
the state is where your data is located and setState is function to reset the state from anywhere,
so on your code,
const [jobseekers, allUsers] = React.useState([]); // change string to array
jobseekers is the variable where your data is located and allUsers is the function to store data into state.
set data to state using allUsers function,
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
allUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
and map from jobseekers
{jobseekers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
Also I would suggest to rename your state and setState as,
const [allUsers, setAllUsers] = React.useState([]);
You didn't pass the value of response to allUsers, instead, you just created a new variable. So change
const allUsers = response.data;
to:
allUsers(response.data)
Besides, you can also improve the way that you have used useState. You have initialized it as an empty string while you'll probably store an array from response in jobseekers. So, initialize it as an empty array.
const [jobseekers, allUsers] = React.useState([]);

Javascript - Return json from fetch in an Object

I'm trying to make an application to get the recipes from https://edamam.com and I'm using fetch and Request object.
I need to make 3 request, and i thought that most beautiful way for do it is make an Object and a method that return the data in JSON.
I declarated into constructor a variable called this.dataJson, and i want to save there the data in JSON from the response. For that purpose i use this.
The problem is that i have a undefined variable.
.then( data => {this.dataJson=data;
console.log(data)} )
This is all my code.
class Recipe{
constructor(url){
this.url=url;
this.dataJson;
this.response;
}
getJson(){
var obj;
fetch(new Request(this.url,{method: 'GET'}))
.then( response => response.json())
.then( data => {this.dataJson=data;
console.log(data)} )
.catch( e => console.error( 'Something went wrong' ) );
}
getData(){
console.log("NO UNDFEIND"+this.dataJson);
}
}
const pa= new Recipe('https://api.edamam.com/search?...');
pa.getJson();
pa.getData();
I'm new studying OOP in JS and more new in Fetch requests...
If you guys can help me... Thanks very much!
Here's a solution using async-await (and a placeholder API):
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
// the async keyword ensures that this function returns
// a Promise object -> we can use .then() later (1)
async getJson() {
try {
const response = await fetch(new Request(this.url, {
method: 'GET'
}))
const json = await response.json()
this.dataJson = json
} catch (e) {
console.error('Something went wrong', e)
}
}
getData() {
console.log("NO UNDFEIND:", this.dataJson);
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// 1 - here we can use the "then", as pa.getJson() returns
// a Promise object
pa.getJson()
.then(() => {
pa.getData()
});
If we want to stay closer to your code, then:
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
getJson() {
// var obj; // not needed
// the "fetch" always returns a Promise object
return fetch(new Request(this.url, { // return the fetch!
method: 'GET'
}))
.then(response => response.json())
.then(data => {
this.dataJson = data;
// console.log(data) // not needed
})
.catch(e => console.error('Something went wrong'));
}
getData() {
console.log("NO UNDFEIND:", this.dataJson); // different syntax here
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// using "then", because the "fetch" returned a Promise object
pa.getJson()
.then(() => {
pa.getData();
});
The problem with your original code is that you initiate the request (pa.getJson()) and then immediately (on the next line) you want to read the data (pa.getData()). pa.getData() is called synchronously (so it happens in milliseconds), but the request is asynchronous - the data needs time to arrive (probably hundreds of milliseconds) - so, it's not there when you try to read it (it simply hasn't arrived yet).
To avoid this you have to use a technique to handle this asynchronous nature of the request:
use a callback function (blee - so last decade)
use a Promise object with then() (much better) or async-await (yeee!)
and call the pa.getData() when the response has arrived (inside the callback function, in the then() or after awaiting the result).

How could I pass JSON object array result to my api URL? (In REACT)

I have to fetch 2 api from backend, and try to get the result from this two. but, at the moment, the JSON result I get from the first API is object Array in JSON. I need to pass the id from first API(using setState) to second API for path variables. But when I do in my way, it fail to retrieve the data. Consider the code below:
componentDidMount(){
// console.log(loginEmail)
fetch(`http://localhost:9000/api/item/list`,)
.then((resp)=>{
resp.json().then((res)=>{
console.log(res.data);
// localStorage.setItem('id', res.data.user_info.id);
this.setState({data: res.data});
}
)
})
const id = this.state.data.id;
fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
.then((resp)=>{
resp.json().then((res)=>{
console.log(res);
// localStorage.setItem('id', res.data.user_info.id);
this.setState({res});}
)
})
}
The problem is that fetch returns a Promise so, at the line
const id = this.state.data.id;
You do not have data populated yet.
You have to concatenate the two requests in a way like the following:
componentDidMount() {
fetch(`http://localhost:9000/api/item/list`)
.then((resp) => {
// return the id
})
.then((id) => {
fetch(`http://localhost:9000/api/item/photo/view/${id}`)
.then((resp) => {
// do what you need with the result
})
})
}
Fetch is asynchronous, which means javascript will
fetch data on the first call with no waiting, and continue
to the second fetch call where the id is not defined or Null.
In order to fix that you can use promises as follow
My code example
import React from "react";
class Home extends React.Component {
constructor() {
super();
this.state = {
res: [],
}
}
// http://jsonplaceholder.typicode.com/users
fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((resp) => {
resp.json().then((res) => {
console.log(res);
// localStorage.setItem('id', res.data.user_info.id);
resolve(res);
}
)
})
})
}
async componentDidMount() {
let data = await this.fetchData("http://jsonplaceholder.typicode.com/users");
console.log("data :", data);
let id = data[0].id;
console.log("Id :", id);
let newData = await this.fetchData(`http://jsonplaceholder.typicode.com/users/${id}`);
this.setState({ res: newData });
}
render() {
return (
<div>
Call API
</div>
)
}
}
export default Home
Adapted on your code
fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((resp) => {
resp.json().then((res) => {
console.log(res.data);
// localStorage.setItem('id', res.data.user_info.id);
resolve(res.data);
}
)
})
})
}
async componentDidMount() {
// console.log(loginEmail)
let data = await this.fetchData("http://localhost:9000/api/item/list");
let id = data.id;
let newData = await this.fetchData(`http://localhost:9000/api/item/photo/view/${id}`);
this.setState({ res: newData });
}
You need to make sure that each id gets its relevant results.
async componentDidMount() {
await fetch(`http://localhost:9000/api/item/list`)
.then(async (resp) => {
let req_ = resp.map((item)=>{
return await fetch(`http://localhost:9000/api/item/photo/view/${item.id}`)
})
let result = Promise.all(req_)
console.log(result)
})
}

how to access nested data by nesting fetch calls?

I'm having trouble understanding the best approach to this.
My goal is to display nested data.
I use fetch on this url - https://horizons-json-cors.s3.amazonaws.com/products.json
which takes me to a page that contains json. inside the json is 3 urls. each url contains the data that I need to get to.
So far, I've accessed the first layer, and now have an array of the item urls. I guess I don't understand how to fetch the data while im inside the outter fetch call.
Here's my code thus far (the result is an array of urls, where each url contains the data I need.) :
componentDidMount() {
console.log('Fetch');
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
var productUrlArr = [];
for (var i = 0; i < json.length; i++) {
productUrlArr.push(json[i].url);
}
.catch((err) => {
console.log('error', err);
});
}
If you guys could help me out and really walk through how to access the next level of data, I would really, really appreciate it.
You can Fetch Data for Inner URLs this way too,
// 1. Outer Fetch call initiated here
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then(res => {
return res.json()
})
.then(res => {
// 2. array for storing url's retrieved from response
var urlArray = []
if (res.length > 0) {
// 3. Push url inside urlArray
res.map(data => urlArray.push(data.url))
}
// 4. an array of urls
return urlArray
})
.then(urls => {
// Return an promise which will return "JSON response" array for all URLs.
// Promise.all means “Wait for these things” not “Do these things”.
return Promise.all(urls.map(url => {
// Take url fetch response, return JSON response
return fetch(url).then(res => res.json())
}
))
})
.then(res => {
// Store all objects into array for later use
var objArr = res; return objArr
})
//.then(...)
You have a little error in your code.
It's missing }) before .catch
With it you can use your data in the array.
componentDidMount(){
console.log('Fetch');
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
var productUrlArr = [];
for (var i = 0; i < json.length; i++) {
productUrlArr.push(json[i].url);
}
console.log(productUrlArr);
}).catch((err) => {
console.log('error', err);
});
}
Hope it helps.
It simple. First get all the url first like you did. Then map and pass it into Promise.all.
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
Promise.all(json.map(product =>
fetch(product.url).then(resp => resp.text())
)).then(texts => {
// catch all the data
})
}).catch((err) => {
console.log('error', err);
});

Ionic 2 - Passing ID from json to child (details) page

I have a provider service that calls get requests from my API. I then have a listing page whereby you can scroll though many recipes. What I am struggling with is taking the ID of each recipe and passing it to the details page as this needs to be included within.
My service request is for the listing is
loadCategory1() {
var url = "http://api.yummly.com/v1/api/recipes?_app_id=////&_app_key=////";
if (this.Category1) {
return Promise.resolve(this.Category1);
}
return new Promise(resolve => {
this.http.get(url + "&allowedAllergy[]=396^Dairy-Free&allowedAllergy[]=393^Gluten-Free&maxResult=50&start=10")
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.Category1 = data.matches;
resolve(this.Category1);
});
});
}
and I currently have a separate one for my details as well
loadDetails() {
if (this.details) {
return Promise.resolve(this.details);
}
return new Promise(resolve => {
this.http.get('http://api.yummly.com/v1/api/recipe/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364?_app_id=//////&_app_key=//////')
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.details = data;
resolve(this.details);
});
});
}
As you can see in the details request i have French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364 This needs to be dynamic by taking the ID from each recipe. Example is below.
Within each .ts file I have the following
loadRecipes(){
this.apiAuthentication.loadCategory1()
.then(data => {
this.api = data;
});
}
This allows me to call the request.
I'm at the point now where I have no clue what to do so some help would be great.
Your DetailsService can be something like this:
loadDetails(detailsId: string) {
return new Promise(resolve => {
this.http.get('http://api.yummly.com/v1/api/recipe/'+detailsId+'?_app_id=//////&_app_key=//////')
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.details = data;
resolve(this.details);
});
});
}
Navigate to DetailsPage with arguments:
this.navCtrl.push(DetailsPage,{
recipe: recipe
});
And you can call DetailsService inside DetailsPage by using code like this:
loadDetails(){
this.apiAuthentication.loadDetails(this.recipe.id)
.then(data => {
this.details = data;
});
}