Skip to content

Instantly share code, notes, and snippets.

@estrattonbailey
Created March 13, 2017 17:30
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 estrattonbailey/e4bf931cf70c943a2e7f98307d1a0b71 to your computer and use it in GitHub Desktop.
Save estrattonbailey/e4bf931cf70c943a2e7f98307d1a0b71 to your computer and use it in GitHub Desktop.
Merging Redux Stores
import { createStore, combineReducers } from 'redux'
import action from 'action-helper'
const TOGGLE_PLAYING_STATE = 'TOGGLE_PLAYING_STATE'
const SET_CURRENT_TIME = 'SET_CURRENT_TIME'
const SET_DURATION = 'SET_DURATION'
const SET_VOLUME = 'SET_VOLUME'
const initialState = {
playing: false,
percent: 0,
duration: 0,
currentTime: 0,
volume: 1,
}
const player = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_PLAYING_STATE:
return Object.assign({}, state, {
playing: action.playing,
})
case SET_CURRENT_TIME:
return Object.assign({}, state, {
currentTime: action.currentTime,
})
case SET_DURATION:
return Object.assign({}, state, {
duration: action.duration,
})
case SET_VOLUME:
return Object.assign({}, state, {
volume: action.volume,
})
default:
return state
}
}
export const actions = {
togglePlayingState: action('TOGGLE_PLAYING_STATE', 'playing'),
setCurrentTime: action('SET_CURRENT_TIME', 'currentTime'),
setDuration: action('SET_DURATION', 'duration'),
setVolume: action('SET_VOLUME', 'volume'),
}
export const store = createStore(
combineReducers({
podcast: player,
})
)
/**
* Create a permanent store
* for future reducers, currently
* only used to attach global app
* state to local redux state.
*/
store.asyncReducers = {}
/**
* Mount a new reducer (state object)
* onto the podcast redux instance
*/
export const mergeReducers = (name, reducer) => {
store.asyncReducers[name] = reducer
const reducers = combineReducers({
podcast: player,
...store.asyncReducers,
})
store.replaceReducer(reducers)
}
import React from 'react'
import { Provider, connect } from 'react-redux'
/**
* Local podcast state
*/
import { store, mergeReducers } from './store'
/**
* Main player
*/
import Player from './Player'
/**
* Inserts global static state props
* and introduces a new Redux context
* specific to the podcast component.
*
* All other connect() in this file
* connect to this store.
*/
const Podcast = ({ data, globals }) => {
mergeReducers('globals', () => globals)
return (
<Provider store={store}>
<Player {...data}/>
</Provider>
)
}
/**
* Connecting to global app state
* to get a couple globals from the
* static global state
*/
export default connect(
state => ({
globals: state.globals,
}),
null
)(Podcast)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment