Steps for Transferring a Const from One File to Another

I am facing an issue with passing the const clouds variable from one file to another.

There seems to be something I am overlooking and I have been looking at this for too long - I really appreciate your help!

Source: getAVWXData.js

import axios from 'axios'

export function getAVWXData() {

  axios.get(
    https://some_url
  )
  .then((response) => {
    const v      = this     
    const res    = response.data
    const clouds = res['Cloud-List'][0.0][1];
    console.log('Give me Clouds! ' + clouds) // <-- This works
  })
}

Destination:

import { getAVWXData } from './get-avwx-data'

getAVWXData()
console.log('Give me Clouds! ' + getAVWXData.clouds) // < Returns undefined!

Answer №1

In order to retrieve the Cloud data, you need to create a promise that returns a value:

import axios from 'axios'

export function fetchCloudData() {

  return axios.get(
    https://some_url
  )
  .then((response) => {
    const clouds = this     
    const responseData = response.data
    return responseData['Cloud-List'][0.0][1];
  })
}

Additionally, utilize the following code snippet to access and display the Cloud data:

import { fetchCloudData } from './fetch-cloud-data'

fetchCloudData().then((result) => {
  console.log('Cloud information: ' + result.result) // <- This should output the Cloud value
})

Answer №2

The issue at hand is that the function getAVWXData does not return any data, and the data you are attempting to access is nested within a resolved promise. To retrieve the value of clouds, you will need to follow this pattern:

import axios from 'axios'

export function fetchAVWXData() {

  return axios.get(
    https://some_url
  );
}

and

import { fetchAVWXData } from './fetch-avwx-data'

fetchAVWXData().then((response) => {
  console.log('Show me Clouds! ' + response.data.clouds)
});

It is crucial to wait for the promise to resolve before accessing the data in the response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

What is the process for including an SVG file in my JavaScript .textContent?

I've been struggling to add an exclamation SVG to this section, but for some reason I can't make it work. I've searched on Google for a solution, but haven't found one yet. The SVG file is already downloaded and stored in my project fo ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Is it possible for Yarn to fail to include both ESM and CJS versions of a package during publishing or adding?

Our application is equipped with Parcel and utilizes a UI library consisting of react components. This UI library is built with Rollup and is privately published on NPM. I've been attempting to transition our application to Parcel 2, but I'm fac ...

Using Axios in a Vue component to modify a user's settings

I'm currently working on updating a preference, with the UI example attached below. The default option is set to yes, but I would like to give users the choice to select no as well. I feel like I may be missing something here, so any guidance or assis ...

Enhance numerous animated shapes in Three.js

Just dipping my toes into the world of Three.js and tinkering with it for fun. My goal is to create a simple dynamic full-screen background for a webpage. You can check out the example here: function createHexagon( vertices, color ) { var geometry = n ...

Utilizing Django HTML to interact with JavaScript variables

Currently working on adding data to include in a form using Chart.js within Django. Originally, my code was as follows: home_data.push({x: "{{transaction.transaction_time.month}}/{{transaction.transaction_time.day}} {{transaction.transaction_time.hour ...

What is the proper way to halt a setInterval timer in javaScript by utilizing an eventListener?

I'm working on developing a pomodoro timer similar to the one found on this website TomatoTimer However, I'm uncertain if my current approach is the most effective. This is the function I have created: function setTimer(minutes = "25") { let ...

Error: The function was not passed as a valid function

Currently, I am in the process of creating a concise 'Engine' class to streamline interactions with Three.js. I have restructured the Render() method from the example into this Engine JS class, as shown below: const Engine = function () { cons ...

Updating state in React Native

Four days ago, I started my journey into learning React Native. I've been attempting to pass a property this to another Scene, but unfortunately, I keep running into the error message "_this.setState is not a function". Despite researching similar iss ...

When using VueJs, an error occurs when attempting to pass a dynamically generated array as a string, but there are no issues when the

I'm currently attempting to pass an array to the Draggable Vue component. The array is being generated dynamically from an inside loop, but I keep encountering the error message: Invalid prop: type check failed for prop "list". Expected Array, but rec ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Eliminate parameter from URL

Here is the URL I am working with: http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860 My goal is to redirect to this URL: http://my.site#/homepage To achieve this, I use the following code snippet: import { push } from 'react-router-redux& ...

Creating an embedded message with Discord.js

I'm currently working on creating a Discord bot and my goal is to have it send an embed when the command hy!help is typed. I followed the format provided in the discord.js documentation and so far, this is what my code looks like: const client = new ...

Capture keyboard input using socket.io

My goal is to capture individual keystroke events (keydown and keyup) in a chat client. The current code I have sets up a chat application that sends each message to a mongoDB cluster. However, I want to create a new record for each keystroke event rather ...

Update image source dynamically using AJAX and jQuery

Within my app, there exists a web page that contains numerous images with dynamically generated source URLs obtained by sending get requests to the rails server. Initially, these images are assigned a default source. Upon loading the page, another request ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Unable to change the AJAX variable that was returned

I have a JavaScript/jQuery script that fetches an external HTML page using AJAX and then applies a function to all its text nodes. $.get('webpage.html', function (html) { $(html).find('*').each(function () { $(this).content ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Having trouble extracting data from JSON object with an AJAX request

I have written some code to fetch JSON data from a servlet using an Ajax call. When the success function is executed, I am able to see the response in the console as Object: [{"userId":"dfeterter"}]. However, I am facing difficulty in accessing the value ...