How to Pass a Const from a File to Another

Viewed 573

I'm having trouble passing the following const clouds from one file to another.

I'm totally missing something here and I've been staring at this too long - Your help is greatly appreciated!

From: 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
  })
}

To:

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

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

The problem here is that getAVWXData does not return any data, and also the data you are trying to retrieve is within a resolved promise. In order to get the clouds value, you will need to do something like this:

import axios from 'axios'

export function getAVWXData() {

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

and

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

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

You must wait until the promise is resolved to get the data from the response.

You should return a promise with a value:

import axios from 'axios'

export function getAVWXData() {

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

and:

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

getAVWXData().then((result) => {
  console.log('Give me Clouds! ' + result.result) // <- Should Return a value
})
Related