I need to capture the cartID in a js variable from a JSON response.
So far I have the following code which requests the cart information.
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
The console.log data is formatted like this:
Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me#gmail.com", ................. }]
I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.
Any ideas how to delay until the response is ready and then 'cartID' with the id value?
Because the response if a JSON array, you can try to loop and extract the cartID from each cart object:
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(
data => {
//The response is an array of cart objects. We need to extract the ID from the array
cartID = data[0].id;
//Or loop through the response and extract the ID from each cart object
for (var i = 0; i < data.length; i++) {
cartID = data[i].id;
}
}
)
.catch(error => console.error(error));
Related
I have a problem to find the correct dynamic variable in woocommerce which works with this API,In this API i need to send product Id and Order count which i dont know the correct variable for them in woocommerce.
please tell me the correct dynamic variable of Product ID and Order count in woocommerce.
This is my API:
const options2 = {
method: 'POST',
headers: {
"SettleTypeId": `STID`,
"RRN": `RNN`,
"ApMerchantId:": `MerchantID`,
"Products":
[
{
"ProductId":`${?}`,
"OrderCount":`${?}`
}
]
}
};
fetch('URL', options2)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
You can use Localstorage for that. You can Store productID and Order Count in localStorage and get here.
const options2 = {
method: 'POST',
headers: {
"SettleTypeId": `STID`,
"RRN": `RNN`,
"ApMerchantId:": `MerchantID`,
"Products":
[
{
"ProductId":`${localStorage.getItem("ID")}`,
"OrderCount":`${localStorage.getItem("OrderCount")}`
}
]
}
}
fetch(URL, data)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error.response.data);
});
Thanks!
I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.
const getFlights = async () => {
const token = await getAsyncData("token");
instance({
method: "get",
url: "/api/flights/",
headers: {
Authorization: `Token ${token}`,
},
})
.then(function (response) {
// console.log(response.data.results); // shows an array of JSON objects
return response.data.results; // I've also tried response.data.results.json()
})```
I just want the response returned as a variable that I can use to populate a FlatList component in RN.
const FlightListScreen = () => {
const [list, setList] = useState([]);
const flights = getFlights(); // currently returns as a promise object
Thank you for your help.
I think you have to store the response object directly to the json method. And then with that response you can store it to the variable
.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
})
you are sending token without a bearer. Concrete your token with bearer like this
headers: {
Authorization: "Bearer " + token,
},
and another thing is your response class are not right this should be like this
.then((response) => response.json())
.then((responseJson) => {
API will Resopne here....
}
this is a complete example to call API with Token
fetch("/api/flights/", {
method: "GET",
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setState(responseJson.VAlue);
})
.catch((error) => {
alert(error);
});
I am creating an email app that sends messages to other people. Currently, I have it working except for the recipients column. Right now, I hard-coded an email into the recipients column to get it working. The reason is, is the recipients field is supposed to be an array.
What's the best way of passing a value from a user form (multiple addresses separated by commas) into JSON format?
Below is how I have it now.
Thanks!
const element = document.getElementById('sendEmail');
element.addEventListener('click', function() {
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: 'card51short#gmail.com',
subject: document.querySelector('#compose-subject').value,
body: document.querySelector('#compose-body').value
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
});
}
const element = document.getElementById('sendEmail');
element.addEventListener('click', function() {
const emailsFromForm = [ // NEW
document.querySelector('#email1').value, // NEW
document.querySelector('#email2').value // NEW
] // NEW
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: emailsFromForm, // EDITED
subject: document.querySelector('#compose-subject').value,
body: document.querySelector('#compose-body').value
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
});
}
I am making an app where I receive data from an API. Once I get this data I want to make another call to the same API with the endpoint that I got from the first call.
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
})
})
this.setState(()=>{
return{
data: json
}
})
})
I am making two fetch requests here but the problem is the data from the first response is output after second fetch request. Also the state: data gets set before state: recipe and the components render with the data from state: data.
render(){
return(
<div className="my-container">
<EnterCalorie getData={this.getData}/>
<MealData data={this.state.data} recipe={this.state.recipe}/>
</div>
)
}
How can i make sure both get passed down at the same time?
In line 3 return return response.json() instead of nothing (undefined).
Update:
const toJson = response => response.json()
fetch(req)
.then(toJson)
.then(json => {
this.setState(() => {
return {
data: json
}
})
return json
})
.then((json) => {
console.log(json)
const promises = json.meals.map((obj) => {
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url, {
method: 'GET',
headers: header
})
return fetch(req)
.then(toJson)
.then((json) => {
console.log(json);
this.setState((prevState) => ({
recipe: prevState.recipe.push(json)
}))
})
})
return Promise.all(promises)
})
.then(() => {
console.log('job done')
})
You need to map your array into promises. Then use Promise.all to wait for them the get resolved.
There was parenthesis missing from:
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
A sidenote, this whole stuff should be refactored. You're not going to get far with this code style / code complexity.
fetch(req) // req no1
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req) // req no 1 called again
.then((response)=>(
response.json()
)).then((json1)=>{
console.log(json1);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json1)
})
this.setState(()=>{
return{
data: json
})
})
})
})
})
I think you are calling api with same req parameters again in the second fetch call
This is a callback hell, please look for Promise races, and check the all() promise method.
I'm trying to fetch a multiple page api and place the json within an array. I've set it up so it does the required number of fetches and is setting up the correct number of promises. I am getting 50+ different responses. However, when I try to map each of those responses, it only pulls the first set of data and pushes that repetitively to the array. What am I not doing correctly?
var data;
fetch(URL_ARTISTS3,{
method:'GET'
})
.then(response => response.json())
.then(json => {
data =json;
const apiPromises = [];
var pagesRequired = Math.ceil(json.setlists["#total"] / json.setlists["#itemsPerPage"]);
for (let i=pagesRequired; i>0;i--) {
var fetchurl = URL_ARTISTS3 + '?page = ' + i;
apiPromises.push(fetch(fetchurl, {
method: "GET",
body: json
}));
}
Promise.all(apiPromises)
.then(responses => {
var processedResponses = [];
responses.map(response => response.json()
.then(json => {
/****THIS LINE ADDS THE SAME JSON RESPONSE MULTIPLE TIMES*****/
processedResponses.push(json.setlists.setlist);
})
)
console.log('processedResponses: ', processedResponses)
});
I'm not sure it solves the problem, but one issue is that you are logging processedResponses before the promises are resolved.
You can simplify your code a lot by moving the response.json() call:
apiPromises.push(
fetch(fetchurl, {method: "GET", body: json})
.then(response => response.json())
.then(json => json.setlists.setlist);
);
// ...
Promise.all(apiPromises).then(processedResponses => console.log(processedResponses));