Skip to content

Instantly share code, notes, and snippets.

@SebastianHGonzalez
Last active May 1, 2019 17:27
Show Gist options
  • Save SebastianHGonzalez/b440178f7f771e2930fa00974bc7176c to your computer and use it in GitHub Desktop.
Save SebastianHGonzalez/b440178f7f771e2930fa00974bc7176c to your computer and use it in GitHub Desktop.
React User Playlist - Example of fetching and displaying an user's playlist using react hooks
/**
* React Example
* User Playlist
*
* Example of fetching and displaying an user's playlist using react hooks
*
*/
/**
* Copyright 2019 Sebastian Gonzalez
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React, { useState, useEffect } from "react";
import Api from "my-api";
import Config from "my-api-config";
function Song({ title, runTime, reproductions, onRemove }) {
return (
<div>
<h1>{title}</h1>
<span>{runTime}</span>
<span>{reproductions}</span>
<button onClick={onRemove}>X</button>
</div>
);
}
function Playlist({ playlist, setPlaylist }) {
const { songs } = playlist;
return songs.map(song => {
const onRemove = () =>
setPlaylist({ ...playlist, songs: songs.filter(x => x !== song) });
return Song({ ...song, onRemove });
});
}
function UserPlaylist({ user }) {
const [playlist, setPlaylist] = usePlaylist(user);
return Playlist({ playlist, setPlaylist });
}
function usePlaylist(user) {
const [playlist, setPlaylist] = useState({ version: -1, songs: [] });
useApi(
api => {
api.fetchUserPlaylist(user).then(setPlaylist);
},
[user]
);
useApi(
api => {
api.updateUserPlaylist(user, playlist);
},
[playlist.version]
);
return [playlist, setPlaylist];
}
function useApi(f, conditions) {
const api = new Api(Config);
return useEffect(() => f(api), conditions);
}
export default UserPlaylist;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment