Sort albums by year, artist or id

* The store gets a sort key.
 * Action creators and actions are added to set sort key.
 * A component is added which dispatches a reducer to update the state.
 * Album list get the sort key from the state and sort albums on render.
This commit is contained in:
Anders Ytterström 2018-11-21 14:58:11 +01:00
parent ec27589232
commit 3d06ff065d
6 changed files with 56 additions and 0 deletions

View file

@ -1,5 +1,6 @@
export const INIT_ALBUM_LIST = 'INIT_ALBUM_LIST';
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
export const SET_SORT_KEY = 'SET_SORT_KEY';
export const initAlbumList = payload => ({
type: INIT_ALBUM_LIST,
@ -12,3 +13,10 @@ export const setVisibilityFilter = filter => ({
filter,
}
});
export const setSortKey = key => ({
type: SET_SORT_KEY,
payload: {
key,
}
});

View file

@ -1,6 +1,7 @@
import React, { Component } from 'react';
import AlbumListContainer from '../containers/album-list';
import FilterInputContainer from '../containers/filter-input';
import SortSelectContainer from '../containers/sort-select';
export default class App extends Component {
render() {
@ -8,6 +9,7 @@ export default class App extends Component {
<div>
<header>
<h1>Brütal Legend</h1>
<SortSelectContainer />
<FilterInputContainer />
</header>
<AlbumListContainer />

View file

@ -0,0 +1,20 @@
import React, { Component } from 'react';
export default class SortSelect extends Component {
render() {
const { value, handleOnChange } = this.props;
return (
<div>
<label htmlFor="sortBy">Sortera efter</label>
<select
id="sortBy"
value={value}
onChange={evt => handleOnChange(evt.target.value)}>
<option value="id">Inköpsdatum</option>
<option value="artist">Artist</option>
<option value="year">År</option>
</select>
</div>
);
}
}

View file

@ -0,0 +1,14 @@
import React from 'react';
import { connect } from 'react-redux';
import SortSelect from '../components/sort-select';
import {setSortKey} from "../actions";
const mapStateToProps = state => ({
value: state.sortKey
});
const mapDispatchToProps = (dispatch) => ({
handleOnChange: (key) => dispatch(setSortKey(key))
});
export default connect(mapStateToProps, mapDispatchToProps)(SortSelect);

View file

@ -1,8 +1,10 @@
import { combineReducers } from 'redux';
import albums from './albums';
import visibilityFilter from './visibilityFilter';
import sortKey from "./sortKey";
export default combineReducers({
albums,
visibilityFilter,
sortKey,
});

10
src/reducers/sortKey.js Normal file
View file

@ -0,0 +1,10 @@
import {SET_SORT_KEY} from '../actions';
export default (state = 'id', action) => {
switch (action.type) {
case SET_SORT_KEY:
return action.payload.key;
default:
return state;
}
};