My app is a clone of Spotify. I am trying to get it to when the user clicks on a song, it plays on the music player. The song_id stored in a component called SongRow (its in a table). When the user clicks on a SongRow component, it is supposed to send the song_id to the MusicControl (the player) component and update the current song. It updates it, but where I can’t set the state using hooks I can’t have the value dynamically change on the site.
Here is a stripped down pseudocode version.
File1.tsx
// Stored in a table inside a playlist page. Cannot be inside MusicControl
<SongRow onClick={() => setSong("Bloody Stream")}/>
File2.tsx
var songID = "";
setSong(id)
{
songID = id;
}
function MusicControl()
{
return (<>
{songID}
... html code
</>);
}
I’ve tried using useState and useEffect hooks to have it update it dynamically. Even tried making Music control a class based component and making a singleton so I could change the state anywhere.
2
Answers
if the SongRow is inside the MusicControl component, you can directly pass the setSong in the prop:
if they are siblings, you can put the state in the parent component, and send setSong to SongRow and song to MusicControl
Use
Redux
, It provides a global state that can be accessed and modified from any component in your application.Components can dispatch actions to update the global state, and other components can subscribe to changes in the state.