From dc33eed88bc119439225759b6fade9a9e06fb73d Mon Sep 17 00:00:00 2001 From: Asara Date: Fri, 26 Jul 2019 17:07:17 -0400 Subject: [PATCH] You must study this commit for the sake of Mark-san --- src/components/PostList.js | 5 ++++- src/reducers/postsReducer.js | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/components/PostList.js b/src/components/PostList.js index 8b54ce9..d967a5f 100644 --- a/src/components/PostList.js +++ b/src/components/PostList.js @@ -9,7 +9,10 @@ class PostList extends React.Component { this.props.fetchPosts(); } renderList() { - return this.props.posts.map(post => { + const {posts} = this.props + const postKeys = Object.keys(posts.entities) + return postKeys.map(id => { + const post = posts.entities[id] return (
diff --git a/src/reducers/postsReducer.js b/src/reducers/postsReducer.js index e15f4be..2a3c642 100644 --- a/src/reducers/postsReducer.js +++ b/src/reducers/postsReducer.js @@ -1,7 +1,18 @@ -export default (state = [], action) => { +const initialState = { + entities: {}, +}; + +const normalizeEntities = (entities, payloadData) => { + const entitiesMap = {} + payloadData.forEach(post => entitiesMap[post.id] = post) + return {...entities, ...entitiesMap} +} + +export default (state = initialState, action) => { switch (action.type) { case 'FETCH_POSTS': - return action.payload; + const mergedEntities = normalizeEntities(state.entities, action.payload) + return {...state, ...{entities: mergedEntities}} case 'FETCH_POST': return action.payload; default: