I have a products page with a button ( addToCart
) and I use fetch to add the product to req.session.cart
on the server. On the front of the app, I use fetch to communicate with the server and get the req.session.cart
as a returned value. How to assign the fetch results to an outside variable?
let whatevervariablehere
function addToCart(e){
let items = e.target.parentElement.parentElement
// rest of the clicked item code .....
//fetch and send the data to server so you can update session
fetch('sc8', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
title : title,
price : price,
description : description,
id : id
})
}).then(response => response.json()).then((results) => {
//**this is the part I'm talking about**
console.log("|||||results|||||", results)
//**How to get access to "retrievelocalstorage" from outside of this code**
localstorage = window.localStorage.setItem(JSON.stringify(user), JSON.stringify(results));
retrievelocalstorage = JSON.parse(window.localStorage.getItem(JSON.stringify(user))) || "No items in cart, Yet!";
// the below console.log prints the right results
console.log("retrievelocalstorage", retrievelocalstorage)
}) //results function end
.catch(error => console.log(error));
} //end of addTocart Function
// this prints "outside the addToCart" and nothing else.
// it is outside the addToCart fn and the fetch promise.
// can I have access to retrievelocalstorage value out here, out of the
// function and the promise or not?
**console.log("this is outside the addToCart fn", retrievelocalstorage)**
IS it possible to get access to retrievelocalstorage
out side of the results fn?
Edit 1 The console.log("this is outside the addToCart fn", retrievelocalstorage) doesn't print the value of retrievelocalstorage. so the suggestion to add.then(retrievelocalstorage => whatevervariablehere = retrievelocalstorage) is still showing whatevervariable empty in consolelog.
You are in the async context. You should continue working inside the promise:
.then(() => {
// you can get your data from LocalStorage here
})
The code after fetch
works without awaiting results
Or you can wrap async fn to another fn and use async/await
async function() {
await addToCart...
// you can get your data from LocalStorage here
}
You can try to use async/await here so that you don't use .then
and can assign the result to a variable.
async function getResults() {
const result = await fetch(...).json() // your code for fetch
// work with result as a regular variable
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.