Skip to content

Instantly share code, notes, and snippets.

@du5rte
Last active Feb 19, 2017
Embed
What would you like to do?
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