Skip to content

Instantly share code, notes, and snippets.

@mrsum
Last active October 2, 2019 07:55
Show Gist options
  • Save mrsum/831d3aaf1d128d96122c67b3978485d8 to your computer and use it in GitHub Desktop.
Save mrsum/831d3aaf1d128d96122c67b3978485d8 to your computer and use it in GitHub Desktop.
store.js
// Depends
import React, { useState, useReducer, useEffect, useContext } from "react";
// Define Store and initialState
const Store = React.createContext(null);
// Store Provider
export function StoreProvider({ children, reducer, initialState }) {
const [store, dispatch] = useReducer(reducer, initialState);
const [state, setState] = useState({ isLoaded: false });
useEffect(() => {
dispatch({ type: "@init" });
setState({ isLoaded: true });
dispatch({ type: "@check" });
}, []);
return (
<Store.Provider value={{ dispatch, store }}>
{state.isLoaded && children}
</Store.Provider>
);
}
export const connect = (mapState, mapDispatch) => WrappedComponent => props => {
const { store, dispatch } = useContext(Store);
return (
<WrappedComponent
{...props}
{...mapState({ ...store, ...props })}
{...mapDispatch(dispatch, props)}
/>
);
};
// combine async reducers
export const combineReducers = reducer => (state = {}, action) => {
const keys = Object.keys(reducer);
const nextReducers = {};
const nextState = keys.map(reducerKey =>
reducer[reducerKey](state[reducerKey], action, state)
);
keys.forEach((value, index) => {
nextReducers[keys[index]] = nextState[index];
});
return nextReducers;
};
// reducer
import { combineReducers } from '@store';
// Reducers
import global from './global';
export default combineReducers({
global
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment