Skip to content

Instantly share code, notes, and snippets.

@vampaynani
Created May 9, 2018 16:36
Show Gist options
  • Save vampaynani/89302e351b31e8d68c36e62945e11aa1 to your computer and use it in GitHub Desktop.
Save vampaynani/89302e351b31e8d68c36e62945e11aa1 to your computer and use it in GitHub Desktop.
How does redux store works behind the scenes
/*
* reducers/user.js
*/
const userInitialState = {
authToken: null,
userId: null
}
const userReducer = (state = userInitialState, action)=>{
return state;
}
/*
* reducers/app.js
*/
const appInitialState = {
currentView: 'home',
userId: 1
}
const appReducer = (state = appInitialState, action)=>{
return state;
}
const combineReducers = (state) => {
return Object.keys(state).reduce((previous, current) => {
previous[current] = state[current]()
return previous;
}, {});
};
/*
* store.js
*/
// Built in redux functions
const createStore = (reducer, enhancer) => {
const store = Object.assign({}, reducer);
return enhancer(store);
}
const applyMiddleware = (...middlewares) => store => {
return middlewares.reduce((previous, middleware) => {
return middleware(store)
}, {});
};
// Mock middleware
const logger = (store) => {
console.log("LOGGER:", JSON.stringify(store));
return store;
};
// what we actually type in the store.js file
const store = createStore(combineReducers({user: userReducer, app: appReducer}),
applyMiddleware(logger));
// Reduced store
console.log(store);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment