Task
by davidohlund
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
#wrapper {
width: 50%;
position: relative;
box-sizing: border-box;
}
#wrapper * {
box-sizing: border-box;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-bottom: 5px;
padding: 5px;
width: 100%;
}
ol {
background-color: #ccc;
padding-top: 1px;
padding-bottom: 1px;
border-radius: 5px;
padding-left: 0;
}
ol li {
margin: 5px;
text-align: center;
background: #fff;
border-radius: 5px;
font-size: large;
list-style: none;
}
React
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
term: '',
items: [
'A','B','C','D','E'
],
songs: []
}
}
// Do the search if user has pressed ENTER
onKeyUp = (e) => {
if (e.which == 13)
{
this.fetchDataFromAPI(this.state.term);
}
}
fetchDataFromAPI(term) {
fetch(`https://itunes.apple.com/search?term=${term}&media=music`)
.then(response => response.json())
.then(searchResult => searchResult.results)
.then(results => {
// Single out collection names
const collectionNames = results.map(s => s.collectionName);
// Create unique list of collection names, then sort
let uniqueCollectionNames = Array.from(new Set(collectionNames));
uniqueCollectionNames.sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
// Return top 5 collection names
return new Promise((resolve, reject) => resolve(uniqueCollectionNames.slice(0, 5)));
})
.then(sortedSongs => {
// Update state to contain 5 sorted songs
this.setState(state => ({
...state,
songs: sortedSongs
}));
});
}
// Update search term
handleChange = (e) => {
this.setState(state => ({
...state,
term: e.target.value
}));
}
componentDidMount() {
setInterval(() => {
let songsBuffer = this.state.songs.slice();
// If we have song to insert from buffer, do that - otherwise just rotate the current items
const insertSong = songsBuffer.shift(1);
const insert = insertSong != undefined ? insertSong : this.state.items.slice(0, 1)[0];
// Rotate items
const arr = [...this.state.items.slice(1), insert];
// Update state to contain rotated items and refresh render
this.setState(state => ({
items: arr,
songs: songsBuffer
}));
}, 1000);
}
render() {
return (
<div id="wrapper">
<h2>David...