Search Bar Functionality - april1703/SpotiReels GitHub Wiki

Search

The Search bar is contained in the Search page where the user can enter a song/artist/album/friends in the text box. Once the user clicks the search icon on the sidebar, they are taken to the Search page. This is possible through calling Spotify's API. The page updates depending on each character the user types. Once the user clicks on a song, the player hot bar updates with the song that the user chose.

This component allows users to:

  • Search Spotify content (tracks, artists, albums)
  • Search for other users in the system
  • Like/unlike tracks
  • Follow/unfollow users
  • Add tracks to playlists

Functionality

  • The input field's onChange makes sure q updates and calls debouncedSearch to immediately get new values.
  • When there is a break between typing debouncedSearch calls runSearch to gather results.
  • During runSearch, the accessToken prop from App.js is searched for.
  • If there is no token, the status is set to tell the user to log in first.
  • A URL similar to (https://api.spotify.com/v1/search?q=&type=<track|artist|album or comma-list>&limit=12&market=) is used for the Spotify Web API request.
  • Makes a fetch request with header Authorization: Bearer <accessToken>.
  • The results are flattened for simplicity and displayed on cards.
State Variable Description
q Text in the input
type What the user is searching for
status Message string for user to debug
items Rendered search results
liked Keys for UI heart state
accessToken Read from localStorage to call Spotify's API

Backend Interaction

Function Endpoint Description
likeOnServer(trackID POST /spotify/like Sends a like action for a track
unLikeOnServer(trackId POST /spotify/unlike Removes a like from a track
followServer(username) POST /addFollowing Adds a user to the following list
unfollowServer(useername) POST /removeFollowing Removes a user from the following list
fetchFollowing() POST /getFollowing Fetches the list of users the current user follows
searchUsers(query) POST /searchUsers Searches the backend for matching users

Search Flow

  1. User types a query into the search box.
  2. The query is debounced to avoid exessive API calls.
  3. Both Spotify API and backend user search are triggered in parallel.
  4. Results are merged and displayed as cards.
  5. Each card can be:
  • Liked/unliked (tracks)
  • Followed/unfollowed (users)
  • Added to a playlist (tracks)

Authentication

  • Requires valid Spotify access token and refresh token in localStorage
  • Retrieves the current user from the JWT cookie named token
  • Communicates with the backend for likes, followers, and user searches

Dependencies

  • React (hooks: useState, useEffect, useMemo, useRef)
  • Spotify Web API
  • Backend (Node.js) at http://localhost:3001