Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Created September 6, 2017 15:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lmiller1990/8977cea3cca636978625f21ed407760a to your computer and use it in GitHub Desktop.
Save lmiller1990/8977cea3cca636978625f21ed407760a to your computer and use it in GitHub Desktop.
React Redux Async middleware example (use create-react-app)
const asyncActionType = (type) => ({
PENDING: `${type}_PENDING`,
SUCCESS: `${type}_SUCCESS`,
FAILURE: `${type}_FAILURE`,
})
export const API = 'API'
export const GET_ALBUMS = asyncActionType('GET_ALBUMS')
import {API, GET_ALBUMS} from '../action-types'
export const getAlbums = () => ({
type: API,
payload: { url: 'albums', ...GET_ALBUMS }
})
import React, {Component} from 'react'
import {connect} from 'react-redux'
class App extends Component {
render() {
console.log(this.props)
return(
<div>
Ajax pending: {this.props.pending.toString()}
</div>
)
}
}
const mapStateToProps = (state) => {
console.log(state)
return {
pending: state.ui.albumsPending
}
}
export default connect(mapStateToProps, {})(App)
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore, applyMiddleware} from 'redux'
import {Provider} from 'react-redux'
import {apiMiddleware} from './store/middleware/api'
import {getAlbums} from './store/actions/albums'
import rootReducer from './store/reducers'
import App from './components/App'
const store = createStore(rootReducer, applyMiddleware(apiMiddleware))
store.dispatch(getAlbums())
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'))
import axios from 'axios'
import {API} from '../action-types'
const BASE_URL = 'http://localhost:3001/'
export const apiMiddleware = ({dispatch}) => next => action => {
if (action.type !== API) {
return next(action)
}
const {payload} = action
dispatch({ type: payload.PENDING })
axios.get(BASE_URL + payload.url)
.then(response => {
console.log(payload.SUCCESS)
dispatch({ type: payload.SUCCESS, payload: response.data })
})
.catch(err => {
dispatch({ type: payload.FAILURE })
})
}
import {GET_ALBUMS} from '../action-types'
export const albums = (state = [], action) => {
switch (action.type) {
case GET_ALBUMS.SUCCESS:
return [...action.payload]
case GET_ALBUMS.PENDING:
return state
case GET_ALBUMS.FAILURE:
return state
default:
return state
}
}
import {combineReducers} from 'redux'
import {albums} from './albums'
import {ui} from './ui'
export default combineReducers({
albums,
ui
})
import {GET_ALBUMS} from '../action-types'
export const ui = (state = { albumsPending: false }, action) => {
switch (action.type) {
case GET_ALBUMS.PENDING:
return {...state, albumsPending: true}
case GET_ALBUMS.SUCCESS:
return {...state, albumsPending: false}
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment