Created
November 17, 2023 01:43
-
-
Save rossnelson/ef1cb83b29224d4f22139f9ead4c0cce to your computer and use it in GitHub Desktop.
store
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
import Session from 'lib/session'; | |
const store = { | |
state: Session.account ? Session.account : null, | |
reducers: { | |
setAccount(state, account) { | |
return account; | |
} | |
} | |
}; | |
export default store; |
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
import React, { createContext, useContext, useReducer } from 'react'; | |
import Log from 'lib/log'; | |
import _ from 'lodash'; | |
import stores from './stores'; | |
const store = createContext(stores.state); | |
const { Provider } = store; | |
const StateProvider = ({ children }) => { | |
const initialState = {}; | |
const storeNames = Object.keys(stores); | |
storeNames.forEach(name => { | |
initialState[name] = stores[name].state; | |
}); | |
const [s, dispatch] = useReducer((state, action) => { | |
try { | |
const { store: storeName, reducer, value } = action; | |
const reducerMethod = _.get(stores, `${storeName}.reducers.${reducer}`); | |
const partialState = _.get(state, storeName); | |
const newPartialState = reducerMethod(partialState, value); | |
const newState = { ...state }; | |
_.set(newState, storeName, newPartialState); | |
return newState; | |
} catch (err) { | |
Log.error(err, state, action); | |
return state; | |
} | |
}, initialState); | |
return <Provider value={{ state: s, dispatch }}>{children}</Provider>; | |
}; | |
function useStore() { | |
const { state, dispatch } = useContext(store); | |
const actions = {}; | |
const storeNames = Object.keys(stores); | |
storeNames.forEach(name => { | |
const storeActions = {}; | |
const actionNames = Object.keys(stores[name].reducers); | |
actionNames.forEach(actionName => { | |
storeActions[actionName] = value => { | |
dispatch({ | |
store: name, | |
reducer: actionName, | |
value | |
}); | |
}; | |
}); | |
actions[name] = storeActions; | |
}); | |
return { state, actions }; | |
} | |
export { store, useStore, StateProvider }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment