Call Fetch Data from API once

Viewed 618

Fetch is often used to retrieve data from api. But if you want to retrieve this data in every line of the code file, you have to type fetch again and again and iterate through these data. But if i want to call only part of it for example username. Look example:

fetch ('/ API')
         .then ((res) => res.json ())
         .then ((data) => {
         let output = 'Here is my output<br />';
         data.forEach (function (item)
         {
         output + = `$ {item.username}`;
         })
         document.getElementById ('here'). innerHTML = output;

         })

if i want to call $ {item.username} in each place in the file without calling fetch. How to save these data in a variabel and call it every time i want. Sorry for my bad English.

4 Answers

But if you want to retrieve this data in every line of the code file, you have to type fetch again and again and iterate through these data.

You can call fetch one time and keep the response in your local state, things like username usually stay the same so you should not call that endpoint again just to fetch a username because you can take it from your previous response.

It depends on your framework, but you can write window.username = usernameFromFetch on your first call, and you will have access to it every where (which is not the best aproach but it will work).

You can use a memoization function to save the result:

// Stores in memory pairs of request urls (arguments) and its result
const memo = (callback) => {
  const cache = new Map();
  return (...args) => {
    const selector = JSON.stringify(args);
    if (cache.has(selector)) return cache.get(selector);
    const value = callback(...args);
    cache.set(selector, value);
    return value;
  };
};

// Memoize the fetch function. This function 'cachedRequest' should be used across your application
const cachedRequest = memo(fetch);
// Your url to call
const URL = "/API";

// First time the fetch is called, the result will be stored in the memory of 'memo' function. Second time its called, it will be retrieved from the previous in memory result and the fetch call wont be done
cachedRequest(URL).then((response) => {
  console.log({response});
}).catch((error) => {
  console.log({error});
})

Try this using localStorage:

fetch ('/ API')
             .then ((res) => res.json ())
             .then ((data) => {
             // Store
             localStorage.setItem("localData", data);
             // Retrieve
             var data = localStorage.getItem("localData");
             let output = 'Here is my output<br />';
             data.forEach (function (item)
             {
             output + = `$ {item.username}`;
             })
             document.getElementById ('here'). innerHTML = output;

             })

Or use sessionStorage:

fetch ('/ API')
                 .then ((res) => res.json ())
                 .then ((data) => {
                 // Store
                 sessionStorage.setItem("localData", data);
                 // Retrieve
                 var data = sessionStorage.getItem("localData");
                 let output = 'Here is my output<br />';
                 data.forEach (function (item)
                 {
                 output + = `$ {item.username}`;
                 })
                 document.getElementById ('here'). innerHTML = output;

                 })

From what I understand through your question is that you want to access variable item.username globally and from the code it looks to be an array of users with username property.

In this case, you can define a variable object

var data = { usernames = [] };

before your fetch function and the value will be initialized to an empty array and as soon as you fetch('/API') users you can do something like this

data.forEach (function (item)
{
    data.usernames.push(item.username);
})

data.usernames will have your usernames throughout your current JS file.

access by data.usernames[0] data.usernames[1] data.usernames[2] or

let output = 'Here is my output<br />';
data.usernames.forEach(function(username){ 
    output + = `$ {username}`;
})
document.getElementById('here').innerHTML = output;`
Related