How to retrieve and store API response data in JavaScript

I’m working on a JavaScript project where I need to fetch information from an external API service and use that data in other parts of my code. The API call seems to work fine, but I’m having trouble accessing the returned data outside of the callback function.

Here’s my current approach:

const axios = require('axios');

const options = {
  method: 'GET',
  url: 'https://weather-api.p.rapidapi.com/current',
  params: {
    location: 'London',
    units: 'metric'
  },
  headers: {
    'X-RapidAPI-Key': 'your-api-key-here',
    'X-RapidAPI-Host': 'weather-api.p.rapidapi.com'
  }
};

axios.request(options).then(function (response) {
    console.log(response.data);
}).catch(function (error) {
    console.error(error);
});

My goal is to run this daily and store the retrieved information so I can use it throughout my application. Right now when I try to access the data outside the callback, I get undefined. What’s the best way to handle this?

The core issue you’re facing is that JavaScript promises are asynchronous, which means the code after your axios call executes before the API response arrives. You need to restructure your code to handle this properly. One effective approach is to create a dedicated function that returns the promise itself, allowing you to chain operations or use async/await wherever you need the data. For daily data storage, consider implementing a simple caching mechanism using variables or localStorage depending on your environment. You might also want to add error handling to ensure your application gracefully handles API failures or network issues.

What worked for me in a similar situation was implementing a data service pattern. Create a separate module that handles all API interactions and maintains the fetched data in memory. You can set up a simple object or Map to cache responses with timestamps, then check if the data is fresh before making new requests. For daily updates, use setInterval or a cron-like scheduler to refresh the cache automatically. The key is exposing getter methods from your service module that other parts of your application can call synchronously once the initial data is loaded. This approach eliminates the async headaches when you just need to access already-fetched data across different components.

sounds like ur dealing with async issues. try using async/await syntax instead - makes it way easier to work with. wrap ur axios call in an async function and await the response, then u can return the data and use it elsewhere in ur code.