Skip to content

Commit

Permalink
Core Data: Refactor, add comments and avoiding returning new instance…
Browse files Browse the repository at this point in the history
…s in each selector call
  • Loading branch information
youknowriad committed Mar 6, 2018
1 parent 5a20290 commit d741b82
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
2 changes: 1 addition & 1 deletion core-data/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const store = registerStore( MODULE_KEY, {
fulfill() {
wp.apiRequest( { path: '/wp/v2/categories' } ).then( categories => {
store.dispatch( {
type: 'FETCH_CATEGORIES_SUCCESS',
type: 'RECEIVE_CATEGORIES',
categories,
} );
} );
Expand Down
33 changes: 25 additions & 8 deletions core-data/reducer.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
const reducer = ( state, action ) => {
/**
* External dependencies
*/
import { uniqBy } from 'lodash';
import { combineReducers } from 'redux';

/**
* Reducer returning the categories list.
*
* @param {Object} state Current state.
* @param {Object} action Dispatched action.
*
* @return {string} Updated state.
*/
function categories( state = [], action ) {
switch ( action.type ) {
case 'FETCH_CATEGORIES_SUCCESS':
return action.categories.reduce( ( memo, category ) => ( {
...memo,
[ category.id ]: category,
} ), {} );
case 'RECEIVE_CATEGORIES':
return uniqBy(
[
...action.categories,
...state,
],
( category ) => category.id
);
}

return state;
};
}

export default reducer;
export default combineReducers( { categories } );
10 changes: 8 additions & 2 deletions core-data/selectors.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { values } from 'lodash';

/**
* Returns all the available categories.
*
* @param {Object} state Global application state.
*
* @return {Array} Categories List
*/
export function getCategories( state ) {
return values( state );
return state.categories;
}

0 comments on commit d741b82

Please sign in to comment.