Surya
Surya

Reputation: 646

How to Use/Make Callback Function with SetState

constructor(props) {
    super(props);
    this.state=({
        year: (props.location.state && props.location.state.year) || '',
        real_id: ''
    });

I'm setting the 'real_id' state variable to a playlist id here, and it is properly returning the id when I console log it. But when I'm adding tracks to playlist, the 'real_id' is undefined. I understand it is because setState is an asynchronous function but I wasn't sure how to make a 'callback' function for this with passing the 'real_id' variable, as this is my first time using React.

spotifyApi.createPlaylist(this.state.users, { 'name' : "Phaseify " + this.state.year, 'public' : true })
      .then((response) => {
        this.setState({
            real_id: response.id
        });
        console.log('Created playlist!');
      }, function(err) {
        console.log('Something went wrong!', err);
      });

spotifyApi.addTracksToPlaylist({"playlistId": this.state.real_id, "tracks": top_track_ids})
        .then((response) => {
            console.log("CREATED");
        }, function(err){
            console.log("An error", err);
        });

Upvotes: 0

Views: 42

Answers (1)

ravi
ravi

Reputation: 1145

if you are calling functions one after the other, what you can try is setState accepts a callback function which gets called when the state is updated, you can call addTracksToPlaylist function in the callback

spotifyApi.createPlaylist(this.state.users, { 'name' : "Phaseify " + this.state.year, 'public' : true })
      .then((response) => {
        this.setState({
            real_id: response.id
        },function(){
          // callback function which gets called when state is set with real_id
          spotifyApi.addTracksToPlaylist({"playlistId": 
          this.state.real_id, "tracks": top_track_ids})
          .then((response) => {
             console.log("CREATED");
          }, function(err){
             console.log("An error", err);
            });             
        });
        console.log('Created playlist!');
      }, function(err) {
        console.log('Something went wrong!', err);
      });

Upvotes: 1

Related Questions