0
votes

I'm currently trying to fetch some data from an API (AlphaVantage) and passing the data as arguments to an axios.post to my MongoDB but I'm getting and error saying the variable is not defined even tho I can get the value with console.log.

static insertPost(shareName) {
  axios.get(url)
  .then(res => {name = res.data['Meta Data']['2.Symbol'];
  console.log(res.data['Time Series (15min)']['2019-08-02 15:45:00']['1. 
  open']);
  price = res.data['Time Series (15min)']['2019-08-02 15:45:00']['1. open'];
})
.then( res => {
  return axios.post(url, {
    name,
    price
})});}

Getting this error:

Uncaught (in promise) ReferenceError: price is not defined at eval

Even tho name and the console.log are working fine, since they're inside the first promise I don't know whats happening, any suggestions?

1

1 Answers

0
votes

name and price belong to a different scope. To pass it to next chain in .then, you need to return the value

static insertPost(shareName) {
  axios.get(url)
    .then(res => {
      const name = res.data['Meta Data']['2.Symbol']
      console.log(res.data['Time Series (15min)']['2019-08-02 15:45:00']['1.open']);
      const price = res.data['Time Series (15min)']['2019-08-02 15:45:00']['1. open'];
      return { name, price }
    })
    .then(res => {
      return axios.post(url, {
        name: res.name,
        price: res.price
      })
    });
}