I'm learning axios and async calls, please sorry if this is too basic. I have this axios call:
trackComponent.jsx
getTrack(event) {
const {select, userId} = this.props
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/track/${select}/${userId}/${this.props.spotifyToken}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
this.setState({
playlist: res.data.data[0].playlist,
artists: res.data.data[0].artists,
previews: res.data.data[0].previews,
youtube_urls: res.data.data[0].youtube_urls,
})
})
.catch((error) => { console.log(error); });
};
Now, I'm refactoring my code, and I've implemented an apiService in front of all my component calls in order to deal with authorization, like so:
trackComponent.jsx
import {apiService} from '../ApiService'
async track(event) {
if (this.props.isAuthenticated) {
const {userId, spotifyToken} = this.props;
const {artist} = this.state
const tracks = await apiService.getTrack(userId, spotifyToken, artist) ;
this.setState({tracks});
} else {
this.setState({tracks: []});
}
}
an in ApiService.js I have:
async getTrack(userId, spotifyToken, select) {
return this.axios.get(
`${process.env.REACT_APP_WEB_SERVICE_URL}/track/${artist}/${userId}/${spotifyToken}`
);
}
Now how do I tweak this new async track(event) in the component in order to keep my 'response' and set the following states,
playlist: res.data.data[0].playlist,
artists: res.data.data[0].artists,
previews: res.data.data[0].previews,
youtube_urls: res.data.data[0].youtube_urls,
which were being passed as response inside then() of the first getTrack(event)?