Search code examples
reactjsreduxreact-reduxactionredux-thunk

React/Redux - Passing JSON data from one API call to another Redux action using Thunk


I'm new to Redux and I am sending an API request to the Spotify API. I am using Thunk and have an action called FetchCurrentlyPlaying which fetches the current song that is being played.

Within the JSON returned from this API call there is an id number which identifies the artist. When I retrieve this JSON data within FetchCurrentlyPlaying I want to then pass this id number to another Redux action, FetchAlbums.

FetchAlbums will then send another API request to the Spotify API and pass the URL the id of the currently playing artist. This will retrieve other albums by that artist.

How do I pass the id from one action to another?


Solution

  • You can dispatch other actions from your thunk

    const FetchAlbums = albumId => dispatch => axios(albumId)
      .then((data) => {
        dispatch(setAlbum(data));
      });
    
    const FetchCurrentlyPlaying = song => dispatch => axios(song)
      .then((data) => {
        dispatch(setSong(data));
        dispatch(FetchAlbums(data.albumId));
      });