Spotify Clone

28 May 2021 — Written by Jorge Abundis
#React#spotify

Engineered a llightweight wrapper that consumes data from the Spotify API and mimics the Ui and front-end behaviors of the official Spotify Web Player.

Login

We get access to the user's Spotify account data

image info

Web Player

image info

Reducer

I created a reducer to have access to the initial state variable to be able to access from any component. Actions were created to be able to dispatch that sepecific action.

export const DataLayerContext = createContext();

export const DataLayer = ({ initialState, reducer, children }) => (
  <DataLayerContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </DataLayerContext.Provider>
);
export const useDataLayerValue = () => useContext(DataLayerContext);


//

const reducer = (state, action) => {
  console.log(action);

  switch (action.type) {
    case "SET_USER":
      return {
        ...state,
        user: action.user,
      };
    case "SET_TOKEN":
      return {
        ...state,
        token: action.token,
      };

    case "SET_PLAYLISTS":
      return {
        ...state,
        playlists: action.playlists,
      };
    case "SET_SPOTIFY":
      return {
        ...state,
        spotify: action.spotify,
      };
    case "SET_TOP_ARTISTS":
      return {
        ...state,
        top_artists: action.top_artists,
      };
    case "SET_ITEM":
      return {
        ...state,
        item: action.item,
      };
    case "SET_DISCOVER_WEEKLY":
      return {
        ...state,
        discover_weekly: action.discover_weekly,
      };

    case "SET_SAVED_TRACKS":
      return {
        ...state,
        saved_tracks: action.saved_tracks,
      };

    case "SET_CHILL":
      return {
        ...state,
        set_chill: action.set_chill,
      };

    case "SET_PLAYING":
      return {
        ...state,
        playing: action.playing,
      };

    case "CURRENTPLAYLIST_ID":
      return {
        ...state,
        currentplaylist_id: action.currentplaylist_id,
      };

    case "CURRENTPLAYLIST":
      return {
        ...state,
        currentplaylist: action.currentplaylist,
      };

    case "SET_CREATEPLAYLIST":
      return {
        ...state,
        set_createplaylist: action.set_createplaylist,
      };
    default:
      return state;
  }
};

API calls

I have many API calls to be able to mimic the Spotify Web Player. Here is an example of the API call that allows the user to play the specific song that was pressed.

const playSong = (id) => {
    spotify
      .play({
        device_id: [`457f7672b03f467c87c33744a857ed2c`],
        uris: [`spotify:track:${id}`],
      })
      .then((res) => {
        spotify.getMyCurrentPlayingTrack().then((r) => {
          dispatch({
            type: "SET_ITEM",
            item: r.item,
          });
          dispatch({
            type: "SET_PLAYING",
            playing: true,
          });
        });
      });
  };