React/Redux - Pass variable to action

21,633

Solution 1

Don't try to import the id, pass it as a parameter when calling the fetchAlbums action.

Something like:

ACTION:

export const fetchAlbums = (id) => async dispatch => {
  dispatch({ type: "FETCH_ALBUMS_BY_ARTIST"});

  //'43ZHCT0cAZBISjO8DG9PnE'
  spotifyApi.getArtistAlbums(id)
    .then((response) => {
      dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_FULFILLED", payload: response})
    })
    .catch((err) => {
      dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_REJECTED", payload: err})
    });
}

USING ACTION:

This will bind a function to call the fetchAlbums function, allowing you to pass parameters instead of the click event.

<button onClick={() => fetchAlbums(id)}>Fetch Album</button>

Solution 2

What you need to do is when you call the action from your component is to pass th id to the action function.Like this: I will also recommend you to use redux-thunk middleware to handle a-asynchronous actions.

export function fetchAlbums(id) {
  return function(dispatch,id) {
    dispatch({ type: "FETCH_ALBUMS_BY_ARTIST"});

    //'43ZHCT0cAZBISjO8DG9PnE'
    spotifyApi.getArtistAlbums(id)
      .then((response) => {
        dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_FULFILLED", payload: response})
      })
      .catch((err) => {
        dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_REJECTED", payload: err})
      });

  }
}
Share:
21,633
Nick Kinlen
Author by

Nick Kinlen

Updated on December 09, 2021

Comments

  • Nick Kinlen
    Nick Kinlen over 2 years

    I'm new to Redux and working on a project using the Spotify API. I'm sending API calls and retrieving data about the currently playing song.

    I have a separate Redux action that is attempting to grab other albums from the currently playing artist. In my App.js I can access the id of the artist via const id = this.props.currentlyPlaying.id

    I want to pass this variable from App.js to my album action. The action contains the API call and looks like this:

    import SpotifyWebApi from 'spotify-web-api-js';
    import {id} from '../App.js';
    const spotifyApi = new SpotifyWebApi();
    
    export function fetchAlbums() {
      return function(dispatch) {
        dispatch({ type: "FETCH_ALBUMS_BY_ARTIST"});
    
        //'43ZHCT0cAZBISjO8DG9PnE'
        spotifyApi.getArtistAlbums(id)
          .then((response) => {
            dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_FULFILLED", payload: response})
          })
          .catch((err) => {
            dispatch({ type: "FETCH_ALBUMS_BY_ARTIST_REJECTED", payload: err})
          });
    
      }
    }
    

    I've tried to import the id variable but I get an error. What is the proper way to pass a variable from a component to a Redux action? I've also tried to access id directly in the action via this.props, that doesn't work either.