Skip to content

Instantly share code, notes, and snippets.

@du5rte
Last active February 19, 2017 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save du5rte/26f5779f641713a733c07eae3fd17507 to your computer and use it in GitHub Desktop.
Save du5rte/26f5779f641713a733c07eae3fd17507 to your computer and use it in GitHub Desktop.
Redux Image Load
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { actionsCreator } from 'actions'
// References
// http://blog.teamtreehouse.com/learn-asynchronous-image-loading-javascript
@connect(
state => state,
dispatch => actionsCreator(dispatch)
) export default class Image extends Component {
static propTypes = {
loader: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
src: PropTypes.string.isRequired
}
componentWillMount() {
this.handleLoading()
}
handleLoading() {
// register asset state as pending (asset: false)
this.props.actions.loading(this.props.src)
}
handleLoad() {
// set asset state as loaded (asset: true)
this.props.actions.loadedAsync(this.props.src)
}
render() {
return (
<img
src={this.props.src}
width={this.props.width}
height={this.props.height}
style={this.props.style}
onLoad={this.handleLoad.bind(this)}
/>
)
}
}
export function imageLoading(url) {
return {
type: 'IMAGE_LOADING',
url
}
}
export function imageLoaded(url) {
return {
type: 'IMAGE_LOADED',
url
}
}
let initialState = {
ready: false,
list: {}
}
function checkReady(state) {
return {
...state,
ready: (!Object.values(state.list).includes(false)) ? true : false
}
}
export default function loader(state = initialState, action) {
switch (action.type) {
case 'IMAGE_LOADING':
return { ...state, list:{ ...state.list, [action.url]:false } }
case 'IMAGE_LOADED':
return checkReady({ ...state, list:{ ...state.list, [action.url]:true } })
default:
return state
}
}
import {
createStore,
combineReducers,
applyMiddleware,
compose
} from 'redux'
// Middleware
// import thunk from 'redux-thunk'
// import promise from 'redux-promise'
import logger from 'redux-logger'
// Reducers
import client from './client'
import images from './images'
import slider from './slider'
const initialState = {}
const reducers = combineReducers({
apollo: client.reducer(),
images,
slider
})
// Store
const store = createStore(
reducers,
initialState,
compose(
applyMiddleware(/*thunk, promise, */logger()),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
)
export {
client,
store
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment