0

I have a function that gets the exchange rates of some stocks:

export const getRates = (symbole1, symbole2, symbole3) => {
    
    const res = []

    axios.all([
        axios.get(`${baseUrl}/${symbole1}`),
        axios.get(`${baseUrl}/${symbole2}`),
        axios.get(`${baseUrl}/${symbole3}`)
    ])
        .then(axios.spread((data1, data2, data3) => {

            res.push(data1.data)
            res.push(data2.data)
            res.push(data3.data)
             return res
    }))
        .catch(
            err => console.log(err)
        )
}

Inside another file I use the function like this:

useEffect(() => {
        getRates('IBM', 'AAPL', 'MSFT')
            .then(res => {
                console.log(res)
                setStock(res)
            })
            .catch(err => {
                console.log(err)
            })
    }, [])

However, this doesn't work because the second file throws this error:

TypeError: Cannot read property 'then' of undefined

What is the problem here? Can you not return the result like this? Or is there another problem?

thanks

1 Answer 1

2

You are getting the error because you're asking for a promise resolve, but only returning a regular value. You could set up another promise to properly return something your then would understand - OR - you could just return the promise...

export const getRates = (symbole1, symbole2, symbole3) => {
  return axios.all([
    axios.get(`${baseUrl}/${symbole1}`),
    axios.get(`${baseUrl}/${symbole2}`),
    axios.get(`${baseUrl}/${symbole3}`)
  ])

}

useEffect(() => {
  const res = []
  getRates('IBM', 'AAPL', 'MSFT')
    .then(axios.spread((data1, data2, data3) => {
      res.push(data1.data)
      res.push(data2.data)
      res.push(data3.data)
      console.log(res)
      setStock(res)
    }))
    .catch(
      err => console.log(err)
    )

}, [])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.