0

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)?

1 Answer 1

1

Provided the API call executes successfully, tracks (the value you're returning from getTrack) will contain the responses you're looking for.

If you console.log it, you'll see the various fields. At that point, it's just a matter of accessing the values and setting state with them:

const tracks = await apiService.getTrack(userId, spotifyToken, artist);
const firstEntry = tracks.data.data[0];

this.setState({
    playlist: firstEntry.playlist, 
    artists: firstEntry.artists,
    ...
});
Sign up to request clarification or add additional context in comments.

4 Comments

@8-Bit Borges You might also want to not return the raw Axios response from your service, rather you might want to return tracks.data.data[0] or some other formatted object. This allows you to replace Axios or change your API service internally since you don't leak that information out, the API just returns the data needed.
so I just set const res = await apiService.getTrack(userId, spotifyToken, artist);, right?
Yep! That's exactly it
@Milton oh, that is nice. care to share some code providing that solution?

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.