Reputation: 62
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
Upvotes: 0
Views: 191
Reputation: 23654
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)
)
}, [])
Upvotes: 2