Last active
May 27, 2020 11:49
-
-
Save Ivannnnn/30375047aebea5e844a01bc1ffde0375 to your computer and use it in GitHub Desktop.
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
const store = { | |
actions: { | |
play: (dispatch, payload, actions) => { | |
// do some action | |
// payload --> 'abc' | |
dispatch('play', 'arg1', 'arg2') | |
} | |
}, | |
reducer: { | |
play: (_) => ({ ..._ }) | |
}, | |
initialState: {} | |
} | |
const App = () => { | |
const [state, actions] = useStore(store) | |
actions.play('abc') | |
return ... | |
} |
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, { useReducer, useCallback } from 'react' | |
const createReducer = (reducerObj) => { | |
return (state, { type, payload }) => { | |
return reducerObj[type] ? reducerObj[type](state, ...payload) : state | |
} | |
} | |
export default function useStore({ | |
reducer = {}, | |
actions = {}, | |
initialState = {}, | |
}) { | |
const [state, _dispatch] = useReducer( | |
useCallback(createReducer(reducer), [reducer]), | |
initialState | |
) | |
const dispatch = (type, ...payload) => _dispatch({ type, payload }) | |
const proxy = new Proxy(actions, { | |
get: (target, prop) => (payload) => target[prop](dispatch, payload, proxy), | |
}) | |
return [state, proxy] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment