Skip to content

Adds advanced Reddit API tutorial code to examples folder #3691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/advanced/ExampleRedditAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ hide_title: true

# Example: Reddit API

This is the complete source code of the Reddit headline fetching example we built during the [advanced tutorial](README.md).
This is the complete source code of the Reddit headline fetching example we built during the [advanced tutorial](README.md). This code is also in [our repository of examples](https://github.com/reduxjs/redux/tree/master/examples/reddit-api) and can be [run in your browser via CodeSandbox](https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/reddit-api).

## Entry Point

Expand Down
35 changes: 35 additions & 0 deletions examples/reddit-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Redux Reddit API Example

This project template was built with [Create React App](https://github.com/facebookincubator/create-react-app), which provides a simple way to start React projects with no build configuration needed.

Projects built with Create-React-App include support for ES6 syntax, as well as several unofficial / not-yet-final forms of Javascript syntax such as Class Properties and JSX. See the list of [language features and polyfills supported by Create-React-App](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#supported-language-features-and-polyfills) for more information.

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br>
You will also see any lint errors in the console.

### `npm run build`

Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
37 changes: 37 additions & 0 deletions examples/reddit-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "reddit-api",
"version": "0.0.1",
"private": true,
"devDependencies": {
"react-scripts": "^3.0.0"
},
"dependencies": {
"babel-polyfill": "6.26.0",
"cross-fetch": "3.0.4",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.0.2",
"redux": "^4.0.1",
"redux-logger": "3.0.6",
"redux-thunk": "2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "react-scripts test --env=node"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"keywords": [
"react",
"redux",
"reduxjs"
],
"description": "Reddit headline fetching advanced tutorial for Redux."
}
21 changes: 21 additions & 0 deletions examples/reddit-api/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Redux Todos Example</title>
</head>
<body>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` in this folder.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
56 changes: 56 additions & 0 deletions examples/reddit-api/src/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import fetch from "cross-fetch";
export const REQUEST_POSTS = "REQUEST_POSTS";
export const RECEIVE_POSTS = "RECEIVE_POSTS";
export const SELECT_SUBREDDIT = "SELECT_SUBREDDIT";
export const INVALIDATE_SUBREDDIT = "INVALIDATE_SUBREDDIT";
export function selectSubreddit(subreddit) {
return {
type: SELECT_SUBREDDIT,
subreddit
};
}
export function invalidateSubreddit(subreddit) {
return {
type: INVALIDATE_SUBREDDIT,
subreddit
};
}
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
};
}
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
};
}
function fetchPosts(subreddit) {
return dispatch => {
dispatch(requestPosts(subreddit));
return fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json => dispatch(receivePosts(subreddit, json)));
};
}
function shouldFetchPosts(state, subreddit) {
const posts = state.postsBySubreddit[subreddit];
if (!posts) {
return true;
} else if (posts.isFetching) {
return false;
} else {
return posts.didInvalidate;
}
}
export function fetchPostsIfNeeded(subreddit) {
return (dispatch, getState) => {
if (shouldFetchPosts(getState(), subreddit)) {
return dispatch(fetchPosts(subreddit));
}
};
}
24 changes: 24 additions & 0 deletions examples/reddit-api/src/components/Picker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class Picker extends Component {
render() {
const { value, onChange, options } = this.props;
return (
<span>
<h1>{value}</h1>
<select onChange={e => onChange(e.target.value)} value={value}>
{options.map(option => (
<option value={option} key={option}>
{option}
</option>
))}
</select>
</span>
);
}
}
Picker.propTypes = {
options: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
};
16 changes: 16 additions & 0 deletions examples/reddit-api/src/components/Posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React, { Component } from "react";
import PropTypes from "prop-types";
export default class Posts extends Component {
render() {
return (
<ul>
{this.props.posts.map((post, i) => (
<li key={i}>{post.title}</li>
))}
</ul>
);
}
}
Posts.propTypes = {
posts: PropTypes.array.isRequired
};
12 changes: 12 additions & 0 deletions examples/reddit-api/src/configureStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { createLogger } from "redux-logger";
import rootReducer from "./reducers";
const loggerMiddleware = createLogger();
export default function configureStore(preloadedState) {
return createStore(
rootReducer,
preloadedState,
applyMiddleware(thunkMiddleware, loggerMiddleware)
);
}
89 changes: 89 additions & 0 deletions examples/reddit-api/src/containers/AsyncApp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import {
selectSubreddit,
fetchPostsIfNeeded,
invalidateSubreddit
} from "../actions";
import Picker from "../components/Picker";
import Posts from "../components/Posts";
class AsyncApp extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleRefreshClick = this.handleRefreshClick.bind(this);
}
componentDidMount() {
const { dispatch, selectedSubreddit } = this.props;
dispatch(fetchPostsIfNeeded(selectedSubreddit));
}
componentDidUpdate(prevProps) {
if (this.props.selectedSubreddit !== prevProps.selectedSubreddit) {
const { dispatch, selectedSubreddit } = this.props;
dispatch(fetchPostsIfNeeded(selectedSubreddit));
}
}
handleChange(nextSubreddit) {
this.props.dispatch(selectSubreddit(nextSubreddit));
this.props.dispatch(fetchPostsIfNeeded(nextSubreddit));
}
handleRefreshClick(e) {
e.preventDefault();
const { dispatch, selectedSubreddit } = this.props;
dispatch(invalidateSubreddit(selectedSubreddit));
dispatch(fetchPostsIfNeeded(selectedSubreddit));
}
render() {
const { selectedSubreddit, posts, isFetching, lastUpdated } = this.props;
return (
<div>
<Picker
value={selectedSubreddit}
onChange={this.handleChange}
options={["reactjs", "frontend"]}
/>
<p>
{lastUpdated && (
<span>
Last updated at {new Date(lastUpdated).toLocaleTimeString()}.{" "}
</span>
)}
{!isFetching && (
<button onClick={this.handleRefreshClick}>Refresh</button>
)}
</p>
{isFetching && posts.length === 0 && <h2>Loading...</h2>}
{!isFetching && posts.length === 0 && <h2>Empty.</h2>}
{posts.length > 0 && (
<div style={{ opacity: isFetching ? 0.5 : 1 }}>
<Posts posts={posts} />
</div>
)}
</div>
);
}
}
AsyncApp.propTypes = {
selectedSubreddit: PropTypes.string.isRequired,
posts: PropTypes.array.isRequired,
isFetching: PropTypes.bool.isRequired,
lastUpdated: PropTypes.number,
dispatch: PropTypes.func.isRequired
};
function mapStateToProps(state) {
const { selectedSubreddit, postsBySubreddit } = state;
const { isFetching, lastUpdated, items: posts } = postsBySubreddit[
selectedSubreddit
] || {
isFetching: true,
items: []
};
return {
selectedSubreddit,
posts,
isFetching,
lastUpdated
};
}
export default connect(mapStateToProps)(AsyncApp);
14 changes: 14 additions & 0 deletions examples/reddit-api/src/containers/Root.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React, { Component } from "react";
import { Provider } from "react-redux";
import configureStore from "../configureStore";
import AsyncApp from "./AsyncApp";
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
<AsyncApp />
</Provider>
);
}
}
4 changes: 4 additions & 0 deletions examples/reddit-api/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import React from "react";
import { render } from "react-dom";
import Root from "./containers/Root";
render(<Root />, document.getElementById("root"));
61 changes: 61 additions & 0 deletions examples/reddit-api/src/reducers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { combineReducers } from "redux";
import {
SELECT_SUBREDDIT,
INVALIDATE_SUBREDDIT,
REQUEST_POSTS,
RECEIVE_POSTS
} from "./actions";
function selectedSubreddit(state = "reactjs", action) {
switch (action.type) {
case SELECT_SUBREDDIT:
return action.subreddit;
default:
return state;
}
}
function posts(
state = {
isFetching: false,
didInvalidate: false,
items: []
},
action
) {
switch (action.type) {
case INVALIDATE_SUBREDDIT:
return Object.assign({}, state, {
didInvalidate: true
});
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
});
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts,
lastUpdated: action.receivedAt
});
default:
return state;
}
}
function postsBySubreddit(state = {}, action) {
switch (action.type) {
case INVALIDATE_SUBREDDIT:
case RECEIVE_POSTS:
case REQUEST_POSTS:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
});
default:
return state;
}
}
const rootReducer = combineReducers({
postsBySubreddit,
selectedSubreddit
});
export default rootReducer;