Repository: GoThinkster/redux-review
Branch: master
Commit: ee72eba40563
Files: 43
Total size: 69.9 KB
Directory structure:
gitextract_8dxt9i05/
├── .gitignore
├── LICENSE.md
├── README.md
├── package.json
├── public/
│ └── index.html
└── src/
├── agent.js
├── components/
│ ├── App.js
│ ├── Article/
│ │ ├── ArticleActions.js
│ │ ├── ArticleMeta.js
│ │ ├── Comment.js
│ │ ├── CommentContainer.js
│ │ ├── CommentInput.js
│ │ ├── CommentList.js
│ │ ├── DeleteButton.js
│ │ └── index.js
│ ├── ArticleList.js
│ ├── ArticlePreview.js
│ ├── Editor.js
│ ├── Header.js
│ ├── Home/
│ │ ├── Banner.js
│ │ ├── MainView.js
│ │ ├── Tags.js
│ │ └── index.js
│ ├── ListErrors.js
│ ├── ListPagination.js
│ ├── Login.js
│ ├── Profile.js
│ ├── ProfileFavorites.js
│ ├── Register.js
│ └── Settings.js
├── constants/
│ └── actionTypes.js
├── index.js
├── middleware.js
├── reducer.js
├── reducers/
│ ├── article.js
│ ├── articleList.js
│ ├── auth.js
│ ├── common.js
│ ├── editor.js
│ ├── home.js
│ ├── profile.js
│ └── settings.js
└── store.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# See http://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
node_modules
# testing
coverage
# production
build
# misc
.DS_Store
.env
npm-debug.log
.idea
================================================
FILE: LICENSE.md
================================================
MIT License
Copyright (c) 2020 GoThinkster
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# 
[](http://realworld.io)
> ### React + Redux codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the [RealWorld](https://github.com/gothinkster/realworld-example-apps) spec and API.
### [Demo](https://react-redux.realworld.io) [RealWorld](https://github.com/gothinkster/realworld)
Originally created for this [GH issue](https://github.com/reactjs/redux/issues/1353). The codebase is now feature complete; please submit bug fixes via pull requests & feedback via issues.
We also have notes in [**our wiki**](https://github.com/gothinkster/react-redux-realworld-example-app/wiki) about how the various patterns used in this codebase and how they work (thanks [@thejmazz](https://github.com/thejmazz)!)
## Getting started
You can view a live demo over at https://react-redux.realworld.io/
To get the frontend running locally:
- Clone this repo
- `npm install` to install all req'd dependencies
- `npm start` to start the local server (this project uses create-react-app)
Local web server will use port 4100 instead of standard React's port 3000 to prevent conflicts with some backends like Node or Rails. You can configure port in scripts section of `package.json`: we use [cross-env](https://github.com/kentcdodds/cross-env) to set environment variable PORT for React scripts, this is Windows-compatible way of setting environment variables.
Alternatively, you can add `.env` file in the root folder of project to set environment variables (use PORT to change webserver's port). This file will be ignored by git, so it is suitable for API keys and other sensitive stuff. Refer to [dotenv](https://github.com/motdotla/dotenv) and [React](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-development-environment-variables-in-env) documentation for more details. Also, please remove setting variable via script section of `package.json` - `dotenv` never override variables if they are already set.
### Making requests to the backend API
For convenience, we have a live API server running at https://conduit.productionready.io/api for the application to make requests against. You can view [the API spec here](https://github.com/GoThinkster/productionready/blob/master/api) which contains all routes & responses for the server.
The source code for the backend server (available for Node, Rails and Django) can be found in the [main RealWorld repo](https://github.com/gothinkster/realworld).
If you want to change the API URL to a local server, simply edit `src/agent.js` and change `API_ROOT` to the local server's URL (i.e. `http://localhost:3000/api`)
## Functionality overview
The example application is a social blogging site (i.e. a Medium.com clone) called "Conduit". It uses a custom API for all requests, including authentication. You can view a live demo over at https://redux.productionready.io/
**General functionality:**
- Authenticate users via JWT (login/signup pages + logout button on settings page)
- CRU* users (sign up & settings page - no deleting required)
- CRUD Articles
- CR*D Comments on articles (no updating required)
- GET and display paginated lists of articles
- Favorite articles
- Follow other users
**The general page breakdown looks like this:**
- Home page (URL: /#/ )
- List of tags
- List of articles pulled from either Feed, Global, or by Tag
- Pagination for list of articles
- Sign in/Sign up pages (URL: /#/login, /#/register )
- Use JWT (store the token in localStorage)
- Settings page (URL: /#/settings )
- Editor page to create/edit articles (URL: /#/editor, /#/editor/article-slug-here )
- Article page (URL: /#/article/article-slug-here )
- Delete article button (only shown to article's author)
- Render markdown from server client side
- Comments section at bottom of page
- Delete comment button (only shown to comment's author)
- Profile page (URL: /#/@username, /#/@username/favorites )
- Show basic user info
- List of articles populated from author's created articles or author's favorited articles
[](https://thinkster.io)
================================================
FILE: package.json
================================================
{
"name": "react-redux-realworld-example-app",
"version": "0.1.0",
"private": true,
"devDependencies": {
"cross-env": "^5.1.4",
"react-scripts": "1.1.1"
},
"dependencies": {
"history": "^4.6.3",
"marked": "^0.3.6",
"prop-types": "^15.5.10",
"react": "^16.3.0",
"react-dom": "^16.3.0",
"react-redux": "^5.0.7",
"react-router": "^4.1.2",
"react-router-dom": "^4.1.2",
"react-router-redux": "^5.0.0-alpha.6",
"redux": "^3.6.0",
"redux-devtools-extension": "^2.13.2",
"redux-logger": "^3.0.1",
"superagent": "^3.8.2",
"superagent-promise": "^1.1.0"
},
"scripts": {
"start": "cross-env PORT=4100 react-scripts start",
"build": "react-scripts build",
"test": "cross-env PORT=4100 react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
================================================
FILE: public/index.html
================================================
Conduit
================================================
FILE: src/agent.js
================================================
import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';
const superagent = superagentPromise(_superagent, global.Promise);
const API_ROOT = 'https://conduit.productionready.io/api';
const encode = encodeURIComponent;
const responseBody = res => res.body;
let token = null;
const tokenPlugin = req => {
if (token) {
req.set('authorization', `Token ${token}`);
}
}
const requests = {
del: url =>
superagent.del(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
get: url =>
superagent.get(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody),
put: (url, body) =>
superagent.put(`${API_ROOT}${url}`, body).use(tokenPlugin).then(responseBody),
post: (url, body) =>
superagent.post(`${API_ROOT}${url}`, body).use(tokenPlugin).then(responseBody)
};
const Auth = {
current: () =>
requests.get('/user'),
login: (email, password) =>
requests.post('/users/login', { user: { email, password } }),
register: (username, email, password) =>
requests.post('/users', { user: { username, email, password } }),
save: user =>
requests.put('/user', { user })
};
const Tags = {
getAll: () => requests.get('/tags')
};
const limit = (count, p) => `limit=${count}&offset=${p ? p * count : 0}`;
const omitSlug = article => Object.assign({}, article, { slug: undefined })
const Articles = {
all: page =>
requests.get(`/articles?${limit(10, page)}`),
byAuthor: (author, page) =>
requests.get(`/articles?author=${encode(author)}&${limit(5, page)}`),
byTag: (tag, page) =>
requests.get(`/articles?tag=${encode(tag)}&${limit(10, page)}`),
del: slug =>
requests.del(`/articles/${slug}`),
favorite: slug =>
requests.post(`/articles/${slug}/favorite`),
favoritedBy: (author, page) =>
requests.get(`/articles?favorited=${encode(author)}&${limit(5, page)}`),
feed: () =>
requests.get('/articles/feed?limit=10&offset=0'),
get: slug =>
requests.get(`/articles/${slug}`),
unfavorite: slug =>
requests.del(`/articles/${slug}/favorite`),
update: article =>
requests.put(`/articles/${article.slug}`, { article: omitSlug(article) }),
create: article =>
requests.post('/articles', { article })
};
const Comments = {
create: (slug, comment) =>
requests.post(`/articles/${slug}/comments`, { comment }),
delete: (slug, commentId) =>
requests.del(`/articles/${slug}/comments/${commentId}`),
forArticle: slug =>
requests.get(`/articles/${slug}/comments`)
};
const Profile = {
follow: username =>
requests.post(`/profiles/${username}/follow`),
get: username =>
requests.get(`/profiles/${username}`),
unfollow: username =>
requests.del(`/profiles/${username}/follow`)
};
export default {
Articles,
Auth,
Comments,
Profile,
Tags,
setToken: _token => { token = _token; }
};
================================================
FILE: src/components/App.js
================================================
import agent from '../agent';
import Header from './Header';
import React from 'react';
import { connect } from 'react-redux';
import { APP_LOAD, REDIRECT } from '../constants/actionTypes';
import { Route, Switch } from 'react-router-dom';
import Article from '../components/Article';
import Editor from '../components/Editor';
import Home from '../components/Home';
import Login from '../components/Login';
import Profile from '../components/Profile';
import ProfileFavorites from '../components/ProfileFavorites';
import Register from '../components/Register';
import Settings from '../components/Settings';
import { store } from '../store';
import { push } from 'react-router-redux';
const mapStateToProps = state => {
return {
appLoaded: state.common.appLoaded,
appName: state.common.appName,
currentUser: state.common.currentUser,
redirectTo: state.common.redirectTo
}};
const mapDispatchToProps = dispatch => ({
onLoad: (payload, token) =>
dispatch({ type: APP_LOAD, payload, token, skipTracking: true }),
onRedirect: () =>
dispatch({ type: REDIRECT })
});
class App extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.redirectTo) {
// this.context.router.replace(nextProps.redirectTo);
store.dispatch(push(nextProps.redirectTo));
this.props.onRedirect();
}
}
componentWillMount() {
const token = window.localStorage.getItem('jwt');
if (token) {
agent.setToken(token);
}
this.props.onLoad(token ? agent.Auth.current() : null, token);
}
render() {
if (this.props.appLoaded) {
return (
);
}
return (
);
}
}
// App.contextTypes = {
// router: PropTypes.object.isRequired
// };
export default connect(mapStateToProps, mapDispatchToProps)(App);
================================================
FILE: src/components/Article/ArticleActions.js
================================================
import { Link } from 'react-router-dom';
import React from 'react';
import agent from '../../agent';
import { connect } from 'react-redux';
import { DELETE_ARTICLE } from '../../constants/actionTypes';
const mapDispatchToProps = dispatch => ({
onClickDelete: payload =>
dispatch({ type: DELETE_ARTICLE, payload })
});
const ArticleActions = props => {
const article = props.article;
const del = () => {
props.onClickDelete(agent.Articles.del(article.slug))
};
if (props.canModify) {
return (
Edit Article
Delete Article
);
}
return (
);
};
export default connect(() => ({}), mapDispatchToProps)(ArticleActions);
================================================
FILE: src/components/Article/ArticleMeta.js
================================================
import ArticleActions from './ArticleActions';
import { Link } from 'react-router-dom';
import React from 'react';
const ArticleMeta = props => {
const article = props.article;
return (
{article.author.username}
{new Date(article.createdAt).toDateString()}
);
};
export default ArticleMeta;
================================================
FILE: src/components/Article/Comment.js
================================================
import DeleteButton from './DeleteButton';
import { Link } from 'react-router-dom';
import React from 'react';
const Comment = props => {
const comment = props.comment;
const show = props.currentUser &&
props.currentUser.username === comment.author.username;
return (
{comment.author.username}
{new Date(comment.createdAt).toDateString()}
);
};
export default Comment;
================================================
FILE: src/components/Article/CommentContainer.js
================================================
import CommentInput from './CommentInput';
import CommentList from './CommentList';
import { Link } from 'react-router-dom';
import React from 'react';
const CommentContainer = props => {
if (props.currentUser) {
return (
);
} else {
return (
Sign in
or
sign up
to add comments on this article.
);
}
};
export default CommentContainer;
================================================
FILE: src/components/Article/CommentInput.js
================================================
import React from 'react';
import agent from '../../agent';
import { connect } from 'react-redux';
import { ADD_COMMENT } from '../../constants/actionTypes';
const mapDispatchToProps = dispatch => ({
onSubmit: payload =>
dispatch({ type: ADD_COMMENT, payload })
});
class CommentInput extends React.Component {
constructor() {
super();
this.state = {
body: ''
};
this.setBody = ev => {
this.setState({ body: ev.target.value });
};
this.createComment = ev => {
ev.preventDefault();
const payload = agent.Comments.create(this.props.slug,
{ body: this.state.body });
this.setState({ body: '' });
this.props.onSubmit(payload);
};
}
render() {
return (
);
}
}
export default connect(() => ({}), mapDispatchToProps)(CommentInput);
================================================
FILE: src/components/Article/CommentList.js
================================================
import Comment from './Comment';
import React from 'react';
const CommentList = props => {
return (
{
props.comments.map(comment => {
return (
);
})
}
);
};
export default CommentList;
================================================
FILE: src/components/Article/DeleteButton.js
================================================
import React from 'react';
import agent from '../../agent';
import { connect } from 'react-redux';
import { DELETE_COMMENT } from '../../constants/actionTypes';
const mapDispatchToProps = dispatch => ({
onClick: (payload, commentId) =>
dispatch({ type: DELETE_COMMENT, payload, commentId })
});
const DeleteButton = props => {
const del = () => {
const payload = agent.Comments.delete(props.slug, props.commentId);
props.onClick(payload, props.commentId);
};
if (props.show) {
return (
);
}
return null;
};
export default connect(() => ({}), mapDispatchToProps)(DeleteButton);
================================================
FILE: src/components/Article/index.js
================================================
import ArticleMeta from './ArticleMeta';
import CommentContainer from './CommentContainer';
import React from 'react';
import agent from '../../agent';
import { connect } from 'react-redux';
import marked from 'marked';
import { ARTICLE_PAGE_LOADED, ARTICLE_PAGE_UNLOADED } from '../../constants/actionTypes';
const mapStateToProps = state => ({
...state.article,
currentUser: state.common.currentUser
});
const mapDispatchToProps = dispatch => ({
onLoad: payload =>
dispatch({ type: ARTICLE_PAGE_LOADED, payload }),
onUnload: () =>
dispatch({ type: ARTICLE_PAGE_UNLOADED })
});
class Article extends React.Component {
componentWillMount() {
this.props.onLoad(Promise.all([
agent.Articles.get(this.props.match.params.id),
agent.Comments.forArticle(this.props.match.params.id)
]));
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
if (!this.props.article) {
return null;
}
const markup = { __html: marked(this.props.article.body, { sanitize: true }) };
const canModify = this.props.currentUser &&
this.props.currentUser.username === this.props.article.author.username;
return (
{this.props.article.title}
{
this.props.article.tagList.map(tag => {
return (
{tag}
);
})
}
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Article);
================================================
FILE: src/components/ArticleList.js
================================================
import ArticlePreview from './ArticlePreview';
import ListPagination from './ListPagination';
import React from 'react';
const ArticleList = props => {
if (!props.articles) {
return (
Loading...
);
}
if (props.articles.length === 0) {
return (
No articles are here... yet.
);
}
return (
{
props.articles.map(article => {
return (
);
})
}
);
};
export default ArticleList;
================================================
FILE: src/components/ArticlePreview.js
================================================
import React from 'react';
import { Link } from 'react-router-dom';
import agent from '../agent';
import { connect } from 'react-redux';
import { ARTICLE_FAVORITED, ARTICLE_UNFAVORITED } from '../constants/actionTypes';
const FAVORITED_CLASS = 'btn btn-sm btn-primary';
const NOT_FAVORITED_CLASS = 'btn btn-sm btn-outline-primary';
const mapDispatchToProps = dispatch => ({
favorite: slug => dispatch({
type: ARTICLE_FAVORITED,
payload: agent.Articles.favorite(slug)
}),
unfavorite: slug => dispatch({
type: ARTICLE_UNFAVORITED,
payload: agent.Articles.unfavorite(slug)
})
});
const ArticlePreview = props => {
const article = props.article;
const favoriteButtonClass = article.favorited ?
FAVORITED_CLASS :
NOT_FAVORITED_CLASS;
const handleClick = ev => {
ev.preventDefault();
if (article.favorited) {
props.unfavorite(article.slug);
} else {
props.favorite(article.slug);
}
};
return (
{article.author.username}
{new Date(article.createdAt).toDateString()}
{article.favoritesCount}
{article.title}
{article.description}
Read more...
{
article.tagList.map(tag => {
return (
{tag}
)
})
}
);
}
export default connect(() => ({}), mapDispatchToProps)(ArticlePreview);
================================================
FILE: src/components/Editor.js
================================================
import ListErrors from './ListErrors';
import React from 'react';
import agent from '../agent';
import { connect } from 'react-redux';
import {
ADD_TAG,
EDITOR_PAGE_LOADED,
REMOVE_TAG,
ARTICLE_SUBMITTED,
EDITOR_PAGE_UNLOADED,
UPDATE_FIELD_EDITOR
} from '../constants/actionTypes';
const mapStateToProps = state => ({
...state.editor
});
const mapDispatchToProps = dispatch => ({
onAddTag: () =>
dispatch({ type: ADD_TAG }),
onLoad: payload =>
dispatch({ type: EDITOR_PAGE_LOADED, payload }),
onRemoveTag: tag =>
dispatch({ type: REMOVE_TAG, tag }),
onSubmit: payload =>
dispatch({ type: ARTICLE_SUBMITTED, payload }),
onUnload: payload =>
dispatch({ type: EDITOR_PAGE_UNLOADED }),
onUpdateField: (key, value) =>
dispatch({ type: UPDATE_FIELD_EDITOR, key, value })
});
class Editor extends React.Component {
constructor() {
super();
const updateFieldEvent =
key => ev => this.props.onUpdateField(key, ev.target.value);
this.changeTitle = updateFieldEvent('title');
this.changeDescription = updateFieldEvent('description');
this.changeBody = updateFieldEvent('body');
this.changeTagInput = updateFieldEvent('tagInput');
this.watchForEnter = ev => {
if (ev.keyCode === 13) {
ev.preventDefault();
this.props.onAddTag();
}
};
this.removeTagHandler = tag => () => {
this.props.onRemoveTag(tag);
};
this.submitForm = ev => {
ev.preventDefault();
const article = {
title: this.props.title,
description: this.props.description,
body: this.props.body,
tagList: this.props.tagList
};
const slug = { slug: this.props.articleSlug };
const promise = this.props.articleSlug ?
agent.Articles.update(Object.assign(article, slug)) :
agent.Articles.create(article);
this.props.onSubmit(promise);
};
}
componentWillReceiveProps(nextProps) {
if (this.props.match.params.slug !== nextProps.match.params.slug) {
if (nextProps.match.params.slug) {
this.props.onUnload();
return this.props.onLoad(agent.Articles.get(this.props.match.params.slug));
}
this.props.onLoad(null);
}
}
componentWillMount() {
if (this.props.match.params.slug) {
return this.props.onLoad(agent.Articles.get(this.props.match.params.slug));
}
this.props.onLoad(null);
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
return (
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Editor);
================================================
FILE: src/components/Header.js
================================================
import React from 'react';
import { Link } from 'react-router-dom';
const LoggedOutView = props => {
if (!props.currentUser) {
return (
);
}
return null;
};
const LoggedInView = props => {
if (props.currentUser) {
return (
Home
New Post
Settings
{props.currentUser.username}
);
}
return null;
};
class Header extends React.Component {
render() {
return (
{this.props.appName.toLowerCase()}
);
}
}
export default Header;
================================================
FILE: src/components/Home/Banner.js
================================================
import React from 'react';
const Banner = ({ appName, token }) => {
if (token) {
return null;
}
return (
{appName.toLowerCase()}
A place to share your knowledge.
);
};
export default Banner;
================================================
FILE: src/components/Home/MainView.js
================================================
import ArticleList from '../ArticleList';
import React from 'react';
import agent from '../../agent';
import { connect } from 'react-redux';
import { CHANGE_TAB } from '../../constants/actionTypes';
const YourFeedTab = props => {
if (props.token) {
const clickHandler = ev => {
ev.preventDefault();
props.onTabClick('feed', agent.Articles.feed, agent.Articles.feed());
}
return (
Your Feed
);
}
return null;
};
const GlobalFeedTab = props => {
const clickHandler = ev => {
ev.preventDefault();
props.onTabClick('all', agent.Articles.all, agent.Articles.all());
};
return (
Global Feed
);
};
const TagFilterTab = props => {
if (!props.tag) {
return null;
}
return (
{props.tag}
);
};
const mapStateToProps = state => ({
...state.articleList,
tags: state.home.tags,
token: state.common.token
});
const mapDispatchToProps = dispatch => ({
onTabClick: (tab, pager, payload) => dispatch({ type: CHANGE_TAB, tab, pager, payload })
});
const MainView = props => {
return (
);
};
export default connect(mapStateToProps, mapDispatchToProps)(MainView);
================================================
FILE: src/components/Home/Tags.js
================================================
import React from 'react';
import agent from '../../agent';
const Tags = props => {
const tags = props.tags;
if (tags) {
return (
{
tags.map(tag => {
const handleClick = ev => {
ev.preventDefault();
props.onClickTag(tag, page => agent.Articles.byTag(tag, page), agent.Articles.byTag(tag));
};
return (
{tag}
);
})
}
);
} else {
return (
Loading Tags...
);
}
};
export default Tags;
================================================
FILE: src/components/Home/index.js
================================================
import Banner from './Banner';
import MainView from './MainView';
import React from 'react';
import Tags from './Tags';
import agent from '../../agent';
import { connect } from 'react-redux';
import {
HOME_PAGE_LOADED,
HOME_PAGE_UNLOADED,
APPLY_TAG_FILTER
} from '../../constants/actionTypes';
const Promise = global.Promise;
const mapStateToProps = state => ({
...state.home,
appName: state.common.appName,
token: state.common.token
});
const mapDispatchToProps = dispatch => ({
onClickTag: (tag, pager, payload) =>
dispatch({ type: APPLY_TAG_FILTER, tag, pager, payload }),
onLoad: (tab, pager, payload) =>
dispatch({ type: HOME_PAGE_LOADED, tab, pager, payload }),
onUnload: () =>
dispatch({ type: HOME_PAGE_UNLOADED })
});
class Home extends React.Component {
componentWillMount() {
const tab = this.props.token ? 'feed' : 'all';
const articlesPromise = this.props.token ?
agent.Articles.feed :
agent.Articles.all;
this.props.onLoad(tab, articlesPromise, Promise.all([agent.Tags.getAll(), articlesPromise()]));
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
return (
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
================================================
FILE: src/components/ListErrors.js
================================================
import React from 'react';
class ListErrors extends React.Component {
render() {
const errors = this.props.errors;
if (errors) {
return (
{
Object.keys(errors).map(key => {
return (
{key} {errors[key]}
);
})
}
);
} else {
return null;
}
}
}
export default ListErrors;
================================================
FILE: src/components/ListPagination.js
================================================
import React from 'react';
import agent from '../agent';
import { connect } from 'react-redux';
import { SET_PAGE } from '../constants/actionTypes';
const mapDispatchToProps = dispatch => ({
onSetPage: (page, payload) =>
dispatch({ type: SET_PAGE, page, payload })
});
const ListPagination = props => {
if (props.articlesCount <= 10) {
return null;
}
const range = [];
for (let i = 0; i < Math.ceil(props.articlesCount / 10); ++i) {
range.push(i);
}
const setPage = page => {
if(props.pager) {
props.onSetPage(page, props.pager(page));
}else {
props.onSetPage(page, agent.Articles.all(page))
}
};
return (
{
range.map(v => {
const isCurrent = v === props.currentPage;
const onClick = ev => {
ev.preventDefault();
setPage(v);
};
return (
{v + 1}
);
})
}
);
};
export default connect(() => ({}), mapDispatchToProps)(ListPagination);
================================================
FILE: src/components/Login.js
================================================
import { Link } from 'react-router-dom';
import ListErrors from './ListErrors';
import React from 'react';
import agent from '../agent';
import { connect } from 'react-redux';
import {
UPDATE_FIELD_AUTH,
LOGIN,
LOGIN_PAGE_UNLOADED
} from '../constants/actionTypes';
const mapStateToProps = state => ({ ...state.auth });
const mapDispatchToProps = dispatch => ({
onChangeEmail: value =>
dispatch({ type: UPDATE_FIELD_AUTH, key: 'email', value }),
onChangePassword: value =>
dispatch({ type: UPDATE_FIELD_AUTH, key: 'password', value }),
onSubmit: (email, password) =>
dispatch({ type: LOGIN, payload: agent.Auth.login(email, password) }),
onUnload: () =>
dispatch({ type: LOGIN_PAGE_UNLOADED })
});
class Login extends React.Component {
constructor() {
super();
this.changeEmail = ev => this.props.onChangeEmail(ev.target.value);
this.changePassword = ev => this.props.onChangePassword(ev.target.value);
this.submitForm = (email, password) => ev => {
ev.preventDefault();
this.props.onSubmit(email, password);
};
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
const email = this.props.email;
const password = this.props.password;
return (
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
================================================
FILE: src/components/Profile.js
================================================
import ArticleList from './ArticleList';
import React from 'react';
import { Link } from 'react-router-dom';
import agent from '../agent';
import { connect } from 'react-redux';
import {
FOLLOW_USER,
UNFOLLOW_USER,
PROFILE_PAGE_LOADED,
PROFILE_PAGE_UNLOADED
} from '../constants/actionTypes';
const EditProfileSettings = props => {
if (props.isUser) {
return (
Edit Profile Settings
);
}
return null;
};
const FollowUserButton = props => {
if (props.isUser) {
return null;
}
let classes = 'btn btn-sm action-btn';
if (props.user.following) {
classes += ' btn-secondary';
} else {
classes += ' btn-outline-secondary';
}
const handleClick = ev => {
ev.preventDefault();
if (props.user.following) {
props.unfollow(props.user.username)
} else {
props.follow(props.user.username)
}
};
return (
{props.user.following ? 'Unfollow' : 'Follow'} {props.user.username}
);
};
const mapStateToProps = state => ({
...state.articleList,
currentUser: state.common.currentUser,
profile: state.profile
});
const mapDispatchToProps = dispatch => ({
onFollow: username => dispatch({
type: FOLLOW_USER,
payload: agent.Profile.follow(username)
}),
onLoad: payload => dispatch({ type: PROFILE_PAGE_LOADED, payload }),
onUnfollow: username => dispatch({
type: UNFOLLOW_USER,
payload: agent.Profile.unfollow(username)
}),
onUnload: () => dispatch({ type: PROFILE_PAGE_UNLOADED })
});
class Profile extends React.Component {
componentWillMount() {
this.props.onLoad(Promise.all([
agent.Profile.get(this.props.match.params.username),
agent.Articles.byAuthor(this.props.match.params.username)
]));
}
componentWillUnmount() {
this.props.onUnload();
}
renderTabs() {
return (
My Articles
Favorited Articles
);
}
render() {
const profile = this.props.profile;
if (!profile) {
return null;
}
const isUser = this.props.currentUser &&
this.props.profile.username === this.props.currentUser.username;
return (
{profile.username}
{profile.bio}
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
export { Profile, mapStateToProps };
================================================
FILE: src/components/ProfileFavorites.js
================================================
import { Profile, mapStateToProps } from './Profile';
import React from 'react';
import { Link } from 'react-router-dom';
import agent from '../agent';
import { connect } from 'react-redux';
import {
PROFILE_PAGE_LOADED,
PROFILE_PAGE_UNLOADED
} from '../constants/actionTypes';
const mapDispatchToProps = dispatch => ({
onLoad: (pager, payload) =>
dispatch({ type: PROFILE_PAGE_LOADED, pager, payload }),
onUnload: () =>
dispatch({ type: PROFILE_PAGE_UNLOADED })
});
class ProfileFavorites extends Profile {
componentWillMount() {
this.props.onLoad(page => agent.Articles.favoritedBy(this.props.match.params.username, page), Promise.all([
agent.Profile.get(this.props.match.params.username),
agent.Articles.favoritedBy(this.props.match.params.username)
]));
}
componentWillUnmount() {
this.props.onUnload();
}
renderTabs() {
return (
My Articles
Favorited Articles
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ProfileFavorites);
================================================
FILE: src/components/Register.js
================================================
import { Link } from 'react-router-dom';
import ListErrors from './ListErrors';
import React from 'react';
import agent from '../agent';
import { connect } from 'react-redux';
import {
UPDATE_FIELD_AUTH,
REGISTER,
REGISTER_PAGE_UNLOADED
} from '../constants/actionTypes';
const mapStateToProps = state => ({ ...state.auth });
const mapDispatchToProps = dispatch => ({
onChangeEmail: value =>
dispatch({ type: UPDATE_FIELD_AUTH, key: 'email', value }),
onChangePassword: value =>
dispatch({ type: UPDATE_FIELD_AUTH, key: 'password', value }),
onChangeUsername: value =>
dispatch({ type: UPDATE_FIELD_AUTH, key: 'username', value }),
onSubmit: (username, email, password) => {
const payload = agent.Auth.register(username, email, password);
dispatch({ type: REGISTER, payload })
},
onUnload: () =>
dispatch({ type: REGISTER_PAGE_UNLOADED })
});
class Register extends React.Component {
constructor() {
super();
this.changeEmail = ev => this.props.onChangeEmail(ev.target.value);
this.changePassword = ev => this.props.onChangePassword(ev.target.value);
this.changeUsername = ev => this.props.onChangeUsername(ev.target.value);
this.submitForm = (username, email, password) => ev => {
ev.preventDefault();
this.props.onSubmit(username, email, password);
}
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
const email = this.props.email;
const password = this.props.password;
const username = this.props.username;
return (
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Register);
================================================
FILE: src/components/Settings.js
================================================
import ListErrors from './ListErrors';
import React from 'react';
import agent from '../agent';
import { connect } from 'react-redux';
import {
SETTINGS_SAVED,
SETTINGS_PAGE_UNLOADED,
LOGOUT
} from '../constants/actionTypes';
class SettingsForm extends React.Component {
constructor() {
super();
this.state = {
image: '',
username: '',
bio: '',
email: '',
password: ''
};
this.updateState = field => ev => {
const state = this.state;
const newState = Object.assign({}, state, { [field]: ev.target.value });
this.setState(newState);
};
this.submitForm = ev => {
ev.preventDefault();
const user = Object.assign({}, this.state);
if (!user.password) {
delete user.password;
}
this.props.onSubmitForm(user);
};
}
componentWillMount() {
if (this.props.currentUser) {
Object.assign(this.state, {
image: this.props.currentUser.image || '',
username: this.props.currentUser.username,
bio: this.props.currentUser.bio,
email: this.props.currentUser.email
});
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.currentUser) {
this.setState(Object.assign({}, this.state, {
image: nextProps.currentUser.image || '',
username: nextProps.currentUser.username,
bio: nextProps.currentUser.bio,
email: nextProps.currentUser.email
}));
}
}
render() {
return (
Update Settings
);
}
}
const mapStateToProps = state => ({
...state.settings,
currentUser: state.common.currentUser
});
const mapDispatchToProps = dispatch => ({
onClickLogout: () => dispatch({ type: LOGOUT }),
onSubmitForm: user =>
dispatch({ type: SETTINGS_SAVED, payload: agent.Auth.save(user) }),
onUnload: () => dispatch({ type: SETTINGS_PAGE_UNLOADED })
});
class Settings extends React.Component {
render() {
return (
Your Settings
Or click here to logout.
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Settings);
================================================
FILE: src/constants/actionTypes.js
================================================
export const APP_LOAD = 'APP_LOAD';
export const REDIRECT = 'REDIRECT';
export const ARTICLE_SUBMITTED = 'ARTICLE_SUBMITTED';
export const SETTINGS_SAVED = 'SETTINGS_SAVED';
export const DELETE_ARTICLE = 'DELETE_ARTICLE';
export const SETTINGS_PAGE_UNLOADED = 'SETTINGS_PAGE_UNLOADED';
export const HOME_PAGE_LOADED = 'HOME_PAGE_LOADED';
export const HOME_PAGE_UNLOADED = 'HOME_PAGE_UNLOADED';
export const ARTICLE_PAGE_LOADED = 'ARTICLE_PAGE_LOADED';
export const ARTICLE_PAGE_UNLOADED = 'ARTICLE_PAGE_UNLOADED';
export const ADD_COMMENT = 'ADD_COMMENT';
export const DELETE_COMMENT = 'DELETE_COMMENT';
export const ARTICLE_FAVORITED = 'ARTICLE_FAVORITED';
export const ARTICLE_UNFAVORITED = 'ARTICLE_UNFAVORITED';
export const SET_PAGE = 'SET_PAGE';
export const APPLY_TAG_FILTER = 'APPLY_TAG_FILTER';
export const CHANGE_TAB = 'CHANGE_TAB';
export const PROFILE_PAGE_LOADED = 'PROFILE_PAGE_LOADED';
export const PROFILE_PAGE_UNLOADED = 'PROFILE_PAGE_UNLOADED';
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';
export const REGISTER = 'REGISTER';
export const LOGIN_PAGE_UNLOADED = 'LOGIN_PAGE_UNLOADED';
export const REGISTER_PAGE_UNLOADED = 'REGISTER_PAGE_UNLOADED';
export const ASYNC_START = 'ASYNC_START';
export const ASYNC_END = 'ASYNC_END';
export const EDITOR_PAGE_LOADED = 'EDITOR_PAGE_LOADED';
export const EDITOR_PAGE_UNLOADED = 'EDITOR_PAGE_UNLOADED';
export const ADD_TAG = 'ADD_TAG';
export const REMOVE_TAG = 'REMOVE_TAG';
export const UPDATE_FIELD_AUTH = 'UPDATE_FIELD_AUTH';
export const UPDATE_FIELD_EDITOR = 'UPDATE_FIELD_EDITOR';
export const FOLLOW_USER = 'FOLLOW_USER';
export const UNFOLLOW_USER = 'UNFOLLOW_USER';
export const PROFILE_FAVORITES_PAGE_UNLOADED = 'PROFILE_FAVORITES_PAGE_UNLOADED';
export const PROFILE_FAVORITES_PAGE_LOADED = 'PROFILE_FAVORITES_PAGE_LOADED';
================================================
FILE: src/index.js
================================================
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import React from 'react';
import { store, history} from './store';
import { Route, Switch } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
import App from './components/App';
ReactDOM.render((
), document.getElementById('root'));
================================================
FILE: src/middleware.js
================================================
import agent from './agent';
import {
ASYNC_START,
ASYNC_END,
LOGIN,
LOGOUT,
REGISTER
} from './constants/actionTypes';
const promiseMiddleware = store => next => action => {
if (isPromise(action.payload)) {
store.dispatch({ type: ASYNC_START, subtype: action.type });
const currentView = store.getState().viewChangeCounter;
const skipTracking = action.skipTracking;
action.payload.then(
res => {
const currentState = store.getState()
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return
}
console.log('RESULT', res);
action.payload = res;
store.dispatch({ type: ASYNC_END, promise: action.payload });
store.dispatch(action);
},
error => {
const currentState = store.getState()
if (!skipTracking && currentState.viewChangeCounter !== currentView) {
return
}
console.log('ERROR', error);
action.error = true;
action.payload = error.response.body;
if (!action.skipTracking) {
store.dispatch({ type: ASYNC_END, promise: action.payload });
}
store.dispatch(action);
}
);
return;
}
next(action);
};
const localStorageMiddleware = store => next => action => {
if (action.type === REGISTER || action.type === LOGIN) {
if (!action.error) {
window.localStorage.setItem('jwt', action.payload.user.token);
agent.setToken(action.payload.user.token);
}
} else if (action.type === LOGOUT) {
window.localStorage.setItem('jwt', '');
agent.setToken(null);
}
next(action);
};
function isPromise(v) {
return v && typeof v.then === 'function';
}
export { promiseMiddleware, localStorageMiddleware }
================================================
FILE: src/reducer.js
================================================
import article from './reducers/article';
import articleList from './reducers/articleList';
import auth from './reducers/auth';
import { combineReducers } from 'redux';
import common from './reducers/common';
import editor from './reducers/editor';
import home from './reducers/home';
import profile from './reducers/profile';
import settings from './reducers/settings';
import { routerReducer } from 'react-router-redux';
export default combineReducers({
article,
articleList,
auth,
common,
editor,
home,
profile,
settings,
router: routerReducer
});
================================================
FILE: src/reducers/article.js
================================================
import {
ARTICLE_PAGE_LOADED,
ARTICLE_PAGE_UNLOADED,
ADD_COMMENT,
DELETE_COMMENT
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case ARTICLE_PAGE_LOADED:
return {
...state,
article: action.payload[0].article,
comments: action.payload[1].comments
};
case ARTICLE_PAGE_UNLOADED:
return {};
case ADD_COMMENT:
return {
...state,
commentErrors: action.error ? action.payload.errors : null,
comments: action.error ?
null :
(state.comments || []).concat([action.payload.comment])
};
case DELETE_COMMENT:
const commentId = action.commentId
return {
...state,
comments: state.comments.filter(comment => comment.id !== commentId)
};
default:
return state;
}
};
================================================
FILE: src/reducers/articleList.js
================================================
import {
ARTICLE_FAVORITED,
ARTICLE_UNFAVORITED,
SET_PAGE,
APPLY_TAG_FILTER,
HOME_PAGE_LOADED,
HOME_PAGE_UNLOADED,
CHANGE_TAB,
PROFILE_PAGE_LOADED,
PROFILE_PAGE_UNLOADED,
PROFILE_FAVORITES_PAGE_LOADED,
PROFILE_FAVORITES_PAGE_UNLOADED
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case ARTICLE_FAVORITED:
case ARTICLE_UNFAVORITED:
return {
...state,
articles: state.articles.map(article => {
if (article.slug === action.payload.article.slug) {
return {
...article,
favorited: action.payload.article.favorited,
favoritesCount: action.payload.article.favoritesCount
};
}
return article;
})
};
case SET_PAGE:
return {
...state,
articles: action.payload.articles,
articlesCount: action.payload.articlesCount,
currentPage: action.page
};
case APPLY_TAG_FILTER:
return {
...state,
pager: action.pager,
articles: action.payload.articles,
articlesCount: action.payload.articlesCount,
tab: null,
tag: action.tag,
currentPage: 0
};
case HOME_PAGE_LOADED:
return {
...state,
pager: action.pager,
tags: action.payload[0].tags,
articles: action.payload[1].articles,
articlesCount: action.payload[1].articlesCount,
currentPage: 0,
tab: action.tab
};
case HOME_PAGE_UNLOADED:
return {};
case CHANGE_TAB:
return {
...state,
pager: action.pager,
articles: action.payload.articles,
articlesCount: action.payload.articlesCount,
tab: action.tab,
currentPage: 0,
tag: null
};
case PROFILE_PAGE_LOADED:
case PROFILE_FAVORITES_PAGE_LOADED:
return {
...state,
pager: action.pager,
articles: action.payload[1].articles,
articlesCount: action.payload[1].articlesCount,
currentPage: 0
};
case PROFILE_PAGE_UNLOADED:
case PROFILE_FAVORITES_PAGE_UNLOADED:
return {};
default:
return state;
}
};
================================================
FILE: src/reducers/auth.js
================================================
import {
LOGIN,
REGISTER,
LOGIN_PAGE_UNLOADED,
REGISTER_PAGE_UNLOADED,
ASYNC_START,
UPDATE_FIELD_AUTH
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case LOGIN:
case REGISTER:
return {
...state,
inProgress: false,
errors: action.error ? action.payload.errors : null
};
case LOGIN_PAGE_UNLOADED:
case REGISTER_PAGE_UNLOADED:
return {};
case ASYNC_START:
if (action.subtype === LOGIN || action.subtype === REGISTER) {
return { ...state, inProgress: true };
}
break;
case UPDATE_FIELD_AUTH:
return { ...state, [action.key]: action.value };
default:
return state;
}
return state;
};
================================================
FILE: src/reducers/common.js
================================================
import {
APP_LOAD,
REDIRECT,
LOGOUT,
ARTICLE_SUBMITTED,
SETTINGS_SAVED,
LOGIN,
REGISTER,
DELETE_ARTICLE,
ARTICLE_PAGE_UNLOADED,
EDITOR_PAGE_UNLOADED,
HOME_PAGE_UNLOADED,
PROFILE_PAGE_UNLOADED,
PROFILE_FAVORITES_PAGE_UNLOADED,
SETTINGS_PAGE_UNLOADED,
LOGIN_PAGE_UNLOADED,
REGISTER_PAGE_UNLOADED
} from '../constants/actionTypes';
const defaultState = {
appName: 'Conduit',
token: null,
viewChangeCounter: 0
};
export default (state = defaultState, action) => {
switch (action.type) {
case APP_LOAD:
return {
...state,
token: action.token || null,
appLoaded: true,
currentUser: action.payload ? action.payload.user : null
};
case REDIRECT:
return { ...state, redirectTo: null };
case LOGOUT:
return { ...state, redirectTo: '/', token: null, currentUser: null };
case ARTICLE_SUBMITTED:
const redirectUrl = `/article/${action.payload.article.slug}`;
return { ...state, redirectTo: redirectUrl };
case SETTINGS_SAVED:
return {
...state,
redirectTo: action.error ? null : '/',
currentUser: action.error ? null : action.payload.user
};
case LOGIN:
case REGISTER:
return {
...state,
redirectTo: action.error ? null : '/',
token: action.error ? null : action.payload.user.token,
currentUser: action.error ? null : action.payload.user
};
case DELETE_ARTICLE:
return { ...state, redirectTo: '/' };
case ARTICLE_PAGE_UNLOADED:
case EDITOR_PAGE_UNLOADED:
case HOME_PAGE_UNLOADED:
case PROFILE_PAGE_UNLOADED:
case PROFILE_FAVORITES_PAGE_UNLOADED:
case SETTINGS_PAGE_UNLOADED:
case LOGIN_PAGE_UNLOADED:
case REGISTER_PAGE_UNLOADED:
return { ...state, viewChangeCounter: state.viewChangeCounter + 1 };
default:
return state;
}
};
================================================
FILE: src/reducers/editor.js
================================================
import {
EDITOR_PAGE_LOADED,
EDITOR_PAGE_UNLOADED,
ARTICLE_SUBMITTED,
ASYNC_START,
ADD_TAG,
REMOVE_TAG,
UPDATE_FIELD_EDITOR
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case EDITOR_PAGE_LOADED:
return {
...state,
articleSlug: action.payload ? action.payload.article.slug : '',
title: action.payload ? action.payload.article.title : '',
description: action.payload ? action.payload.article.description : '',
body: action.payload ? action.payload.article.body : '',
tagInput: '',
tagList: action.payload ? action.payload.article.tagList : []
};
case EDITOR_PAGE_UNLOADED:
return {};
case ARTICLE_SUBMITTED:
return {
...state,
inProgress: null,
errors: action.error ? action.payload.errors : null
};
case ASYNC_START:
if (action.subtype === ARTICLE_SUBMITTED) {
return { ...state, inProgress: true };
}
break;
case ADD_TAG:
return {
...state,
tagList: state.tagList.concat([state.tagInput]),
tagInput: ''
};
case REMOVE_TAG:
return {
...state,
tagList: state.tagList.filter(tag => tag !== action.tag)
};
case UPDATE_FIELD_EDITOR:
return { ...state, [action.key]: action.value };
default:
return state;
}
return state;
};
================================================
FILE: src/reducers/home.js
================================================
import { HOME_PAGE_LOADED, HOME_PAGE_UNLOADED } from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case HOME_PAGE_LOADED:
return {
...state,
tags: action.payload[0].tags
};
case HOME_PAGE_UNLOADED:
return {};
default:
return state;
}
};
================================================
FILE: src/reducers/profile.js
================================================
import {
PROFILE_PAGE_LOADED,
PROFILE_PAGE_UNLOADED,
FOLLOW_USER,
UNFOLLOW_USER
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case PROFILE_PAGE_LOADED:
return {
...action.payload[0].profile
};
case PROFILE_PAGE_UNLOADED:
return {};
case FOLLOW_USER:
case UNFOLLOW_USER:
return {
...action.payload.profile
};
default:
return state;
}
};
================================================
FILE: src/reducers/settings.js
================================================
import {
SETTINGS_SAVED,
SETTINGS_PAGE_UNLOADED,
ASYNC_START
} from '../constants/actionTypes';
export default (state = {}, action) => {
switch (action.type) {
case SETTINGS_SAVED:
return {
...state,
inProgress: false,
errors: action.error ? action.payload.errors : null
};
case SETTINGS_PAGE_UNLOADED:
return {};
case ASYNC_START:
return {
...state,
inProgress: true
};
default:
return state;
}
};
================================================
FILE: src/store.js
================================================
import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger'
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import { promiseMiddleware, localStorageMiddleware } from './middleware';
import reducer from './reducer';
import { routerMiddleware } from 'react-router-redux'
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
// Build the middleware for intercepting and dispatching navigation actions
const myRouterMiddleware = routerMiddleware(history);
const getMiddleware = () => {
if (process.env.NODE_ENV === 'production') {
return applyMiddleware(myRouterMiddleware, promiseMiddleware, localStorageMiddleware);
} else {
// Enable additional logging in non-production environments.
return applyMiddleware(myRouterMiddleware, promiseMiddleware, localStorageMiddleware, createLogger())
}
};
export const store = createStore(
reducer, composeWithDevTools(getMiddleware()));