Last active
February 24, 2019 07:24
-
-
Save shlomokraus/8029077557be5f5055a7bce9858f067d to your computer and use it in GitHub Desktop.
Music download - hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create app component (no container needed so it just mounts the page) | |
*/ | |
function SongsApp() { | |
return <SongsPage />; | |
} | |
/** | |
* Page component (no props so fetch song list with useSongList hook) | |
*/ | |
function SongsPage() { | |
const { songs } = useSonglist(); | |
return ( | |
<div className="songs-page"> | |
<div className="title">Hooked On Songs</div> | |
<SongList songs={songs} /> | |
</div>) | |
} | |
/** | |
* List component only requires the song list | |
*/ | |
function SongList({ songs }) { | |
return <ul> | |
{songs.map(song => ( | |
<li key={song.id}> | |
<Song song={song} /> | |
</li>)} | |
</ul>; | |
} | |
/** | |
* Song item with download indicator using the useDownloadSong hook | |
*/ | |
function Song({ song }) { | |
return ( | |
<div className="song-item"> | |
<div className="song-title">{song.title}</div> | |
<DownloadBtn id={song.id} /> | |
</div> | |
); | |
} | |
function DownloadBtn({id}) { | |
const {download, downloading } = useDownloadSong(id); | |
return ( | |
<div className="download"> | |
{downloading ? | |
"Downloading..." | |
: <div onClick={()=>download(id)}>Download</div>} | |
</div>); | |
} | |
/** | |
* Fetch songs hook | |
*/ | |
import { useState, useEffect } from "react"; | |
function useSonglist() { | |
const [songs, setSongs] = useState([]); | |
useEffect(() => { | |
Network.get("http://songs.com/get").then(result => setSongs(result)); | |
}, []); | |
return { songs }; | |
} | |
/** | |
* Download song hook | |
*/ | |
function useDownloadSong(id: string) { | |
const [downloading, setDownloading] = useState(false); | |
const download = () => { | |
setDownloading(true); | |
Network.download("http://songs.com/song/" + id).then(result => | |
setDownloading(false) | |
); | |
}; | |
return { downloading, download }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment