jj008
jj008

Reputation: 1083

redux thunk callback function

I'm new to redux/thunk and I'm going through some code that weren't written by me and I'm trying to understand how everything works. When the function refreshPlaylist is dispatched, it has the param id and a callback function. I'm wondering what playlist is referring to in the callback.

Component.jsx

loadData = id => {
    const { dispatch } = this.props;
    dispatch(
        PlaylistThunks.refreshPlaylist(id, playlist => {
            dispatch(PlaylistActions.setPlaylistUnderDisplay(playlist));
        })
    );
}

thunks.js

export const refreshPlaylist = (id, successCallBack) => dispatch => {
    PlayListService.getPlaylist(id)
        .then(response => {
            const playlist = response.data;
            PlayListService.getTracklist(id).then(response2 => {
                playlist.songs = response2.data.items;
                dispatch(Actions.updatePlaylist(playlist));
                if (successCallBack) {
                    successCallBack(playlist);
                }
            });
        })
        .catch(e => console.error(e));

Upvotes: 0

Views: 544

Answers (1)

Oliver
Oliver

Reputation: 237

Big Picture: LoadData is dispatching two actions.

  1. is to fetch the playlist using id. (This action is actually several actions wrapped into one, so we must move over to the Thunks.js to resolve).

  2. is to update the store (view) using (playlist) as a name for the return value from calling refreshPlaylist.

=> setPlaylistUnderDisplay takes playlist and changes the view to display /that/ playlist (after the variable playlist has been set from refreshPlaylist).

In a more granular view:

// In Component.jsx:

you are dispatching two actions. The first one is refreshPlaylist which takes id. After that returns, it's using the reponse value from that action (named playlist) and calling setPlaylistUnderDisplay.

// in thunks.js

const playlist = response.data; // this is naming what the response is from the API call (getPlaylist(id)).

Then getTracklist(id) API call is being fired, the response to that (response2.data.items) is the name of the songs.

At which point dispatch(updatePlaylist(playlist)) // where playlist is the item returned from the first API call (const playlist = response.data;)

Upvotes: 1

Related Questions