Skip to content

Commit

Permalink
feat: store state for posts by category
Browse files Browse the repository at this point in the history
After clicking on each category, users can view posts of the category

Using GET_POSTS_BY_CATEGORY action and redeucer
  • Loading branch information
iamthuypham committed Oct 16, 2017
1 parent d2e996c commit 1191c4f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
12 changes: 12 additions & 0 deletions frontend/src/post/Post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route, Link } from 'react-router-dom';

const Post = props => (
<div>{props.post.author} - {props.post.title} - {props.post.body} - {props.post.voteScore}</div>
)
Post.PropTypes = {
post: PropTypes.object.isRequired
}

export default Post
17 changes: 17 additions & 0 deletions frontend/src/post/action.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const GET_POSTS_BY_CATEGORY = 'GET_POSTS_BY_CATEGORY'

const getPostsByCategory = posts => ({
type: GET_POSTS_BY_CATEGORY,
posts
}
)

export function fetchPostsByCategory(category) {
return function (dispatch) {
const url = `${process.env.REACT_APP_BACKEND}/${category}/posts`
return fetch( url, { headers: { 'Authorization': 'whatever-you-want' }, credentials: 'include' })
.then((res) => res.json())
.then(data => dispatch(getPostsByCategory(data))
);
};
}
26 changes: 26 additions & 0 deletions frontend/src/post/reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { combineReducers } from 'redux'

import {
GET_POSTS_BY_CATEGORY,
} from './action'

function getPostsByCategoriesReducer (state={
isFetching: true,
posts: []
}, action) {
const { posts } = action
console.log(posts)
switch (action.type) {
case GET_POSTS_BY_CATEGORY:
return Object.assign({}, state, {
isFetching: false,
posts
})
default:
return state
}
}

export default combineReducers({
getPostsByCategoriesReducer
})

0 comments on commit 1191c4f

Please sign in to comment.