Redux Fetch Example
Simple timeout example
by Allie Yu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-15.0.1.js"></script>
<script src="https://fb.me/react-dom-15.0.1.js"></script>
<link rel="stylesheet" href="https://my.stackla.com/media/components/stackla-uikit/dist/uikit.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.1.0/redux-thunk.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
SCSS
.indicator {
font-size: 36px;
height: 50px;
margin-bottom: 10px;
}
Babel + JSX
const {Provider, connect} = ReactRedux;
const {createStore, applyMiddleware} = Redux;
const thunk = ReduxThunk.default;
function fetchPostsRequest(){
return {
type: "FETCH_REQUEST"
}
}
function fetchPostsSuccess(payload) {
return {
type: "FETCH_SUCCESS",
payload
}
}
function fetchPostsError() {
return {
type: "FETCH_ERROR"
}
}
const reducer = (state = {}, action) => {
switch (action.type) {
case "FETCH_REQUEST":
return state;
case "FETCH_SUCCESS":
return {...state, posts: action.payload};
default:
return state;
}
}
function fetchPostsWithRedux() {
return (dispatch) => {
dispatch(fetchPostsRequest());
return fetchPosts().then(([response, json]) =>{
if(response.status === 200){
dispatch(fetchPostsSuccess(json))
}
else{
dispatch(fetchPostsError())
}
})
}
}
function fetchPosts() {
const URL = "https://jsonplaceholder.typicode.com/posts";
return fetch(URL, { method: 'GET'})
.then( response => Promise.all([response, response.json()]));
}
class App extends React.Component {
componentDidMount(){
this.props.fetchPostsWithRedux()
}
render(){
return (
<ul>
{
this.props.posts &&
this.props.posts.map((post) =>{
return(
<li>{post.title}</li>
)
})
}
</ul>
)
}
}
function mapStateToProps(state){
return {
posts: state.posts
}
}
let Container = connect(mapStateToProps, {fetchPostsWithRedux})(App);
const store = createStore(
reducer,
applyMiddleware(thunk)
);
ReactDOM.render(
<Provider store={store}>
<Container/>
</Provider>,
document.getElementById('container')
);