Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active May 27, 2020 11:49
Show Gist options
  • Save Ivannnnn/30375047aebea5e844a01bc1ffde0375 to your computer and use it in GitHub Desktop.
Save Ivannnnn/30375047aebea5e844a01bc1ffde0375 to your computer and use it in GitHub Desktop.
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 ...
}
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