I'm trying to get a image data from an API and. To do that I first need to get it's ID and then use it to get the image. To maintain a clean code, I'm using a function to do that, I'm having problems when I try to return the response to the component I call the function.
getNextImageData
export const getNextImageData = () => {
const apiToken = lscache.get('apiToken')
return(
axios({
method: 'get',
url: 'https://myapiurl/images/',
params: {
limit: '1',
doc_cat: ''
},
responseType: 'json'
})
.then(response => {
lscache.set('imageData', response, 30)
axios({
method: 'get',
url: 'https://myapiurl/images/' + response.data[0].id + '/',
})
.then(response => {
return(response.data)
})
})
)
}
MyClass
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
image: undefined
}
}
async componentDidMount() {
const data = await getNextImageData()
this.setState({
image: data,
})
}
render() {
// something
}
}
I receive nothing from the return, when I pasted the code directly into my component, it worked fine, but I want to use it inside a function
I was nesting it wrongly, you don't use a then inside another then, you use them on the same level. And every axios call follows a return statement. Doing so I didn't even need to use async/await, I used another promise.
getNextImageData
export const getNextImageData = () => {
const apiToken = lscache.get('apiToken')
return axios({
method: 'get',
url: 'https://myapiurl/images/',
params: {
limit: '1',
doc_cat: ''
},
responseType: 'json'
})
.then(response => {
lscache.set('imageData', response, 30)
return axios({
method: 'get',
url: 'https://myapiurl/images/' + response.data[0].id + '/',
})
})
.then(response => {
return response.data
})
}
MyClass
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
image: undefined
}
}
componentDidMount() {
getNextImageData()
.then(data => {
this.setState({
image: data,
})
})
}
render() {
// something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With