import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
function CategoryFlatList(props) {
const { error, isLoaded, items } = props.state;
var content;
if (error) {
content =
Error: {error.message}
} else if (!isLoaded) {
content = Loading
} else {
content = (
);
}
return (
{props.title}
{content}
);
}
class App extends Component {
constructor(props) {
super(props);
this.categories = [{type: 'artist', title: 'Artists'},
{type: 'year', title: 'Years'},
{type: 'publisher', title: 'Labels'},
{type: 'country', title: 'Countries'},
{type: 'type', title: 'Album types'},
{type: 'status', title: 'Album statuses'}];
this.state = {};
for (var {type} of this.categories) {
this.state[type] = {
error: null,
isLoaded: false,
items: []
};
}
}
fetchCategory(cat) {
const {restrictions} = this.state;
function getQueryString(params) {
var esc = encodeURIComponent;
return Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
}
const params = Object.assign({}, restrictions, {offset:0, limit:100});
const qs = getQueryString(params);
fetch('/cat/' + cat + (qs ? ('?' + qs) : ''))
.then(res => (res.ok ? res.json() : Promise.reject({message:res.statusText})))
.then(result => {
this.setState({[cat]: {
isLoaded: true,
items: result
}});
})
.catch(error => {
this.setState({[cat]: {
isLoaded: true,
error: error
}});
})
}
fetchAll() {
const {restrictions} = this.state;
console.log(restrictions);
this.categories.map(({type}) => !restrictions[type] && this.fetchCategory(type))
}
componentDidMount() {
this.setState({restrictions: {}});
}
componentDidUpdate(prevProps, prevState) {
if (this.state.restrictions !== prevState.restrictions) {
// Reload category filters on restriction changes
this.fetchAll();
}
}
handleCategoryChange(type, value) {
console.log(type, value);
var restrictions = Object.assign({}, this.state.restrictions);
if (value) {
restrictions[type] = value;
} else {
delete restrictions[type];
}
this.setState({restrictions: restrictions});
}
render() {
return (
Chad Music
{this.categories.map(({type, title}) => (
this.handleCategoryChange(type, e.target.value)}/>
))}
);
}
}
export default App;