Last active
October 2, 2019 07:55
-
-
Save mrsum/831d3aaf1d128d96122c67b3978485d8 to your computer and use it in GitHub Desktop.
store.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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