简体   繁体   中英

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. 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)

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

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');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM