[英]How to store fetch data into a global variable that you can access later?
I have this code below that's pulling all of one specific product type and the array has data that i want to use in a different function.我在下面有这段代码,它提取了所有一种特定的产品类型,并且该数组包含我想在不同的 function 中使用的数据。 How would i go about storing the fetched data into a variable that i can pull into a different function(i need to add a click event and filter to display additional information from this array elsewhere)
我将如何 go 将获取的数据存储到一个我可以拉入不同函数的变量中(我需要添加一个点击事件和过滤器以在其他地方显示来自该数组的其他信息)
const displayProduct = (event) => {
const info =document.getElementById('info')
const ul = document.getElementById('makeup-list')
ul.innerHTML = " "
fetch( `https://makeup-api.herokuapp.com/api/v1/products.json/?product_type=${event.target.value}`)
.then(res => res.json())
//iterate
.then(data => {
data.forEach(data => {
info.innerHTML +=
` <li><a href="#" data-id=>${data.name}</a></li>`
})
You can use localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage您可以使用 localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Save in localStorage:保存在本地存储中:
ul.innerHTML = " "
fetch( `https://makeup-api.herokuapp.com/api/v1/products.json/?product_type=${event.target.value}`)
.then(res => res.json())
//iterate
.then(data => {
localStorage.setItem('myData', data);
....
}
Get the data in another func:在另一个函数中获取数据:
const data = localStorage.getItem('myData');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.