Created
December 29, 2019 12:42
-
-
Save Karnak19/f26a4ecc3c7495bbfb42015deb5007bc to your computer and use it in GitHub Desktop.
This file contains hidden or 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, {useContext, useState, useEffect} from 'react'; | |
| import {ReactReduxContext} from 'react-redux'; | |
| import Content from './Content'; | |
| function useStore() { | |
| const { store } = useContext(ReactReduxContext); | |
| const { getState, dispatch, subscribe } = store; | |
| const [ storeState, setStoreState ] = useState(getState()); | |
| useEffect(() => subscribe(() => { | |
| setStoreState(getState()); | |
| }, [])); | |
| return [storeState, dispatch]; | |
| } | |
| function useSelectors(...selectors) { | |
| const [state] = useStore(); | |
| return selectors.map(selector => selector(state)); | |
| } | |
| function useActionCreators(...creators) { | |
| const [, dispatch] = useStore(); | |
| return creators.map(creator => (...param) => dispatch(creator(...param))) | |
| } | |
| function updateColor(payload) { | |
| return ({ | |
| type: 'UPDATE_COLOR', | |
| payload | |
| }); | |
| } | |
| export default function HookedApp() { | |
| const [color, otherColor] = useSelectors( | |
| state => state.color, | |
| state => state.otherColor | |
| ) | |
| const [updateStoreColor] = useActionCreators(updateColor) | |
| return <Content | |
| color={color} | |
| otherColor={otherColor} | |
| updateColor={updateStoreColor} | |
| text="Hook me" | |
| /> | |
| } |
This file contains hidden or 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 from 'react'; | |
| import { render } from 'react-dom'; | |
| import { createStore } from 'redux' | |
| import { Provider } from 'react-redux'; | |
| import ConnectedApp from './ConnectedApp'; | |
| import HookedApp from './HookedApp'; | |
| import './style.css'; | |
| const initialState = { | |
| color: '#FF8585', | |
| otherColor: '#FFE87A' | |
| } | |
| function reducer(state = initialState, {type, payload}) { | |
| if (type === 'UPDATE_COLOR') { | |
| return {...state, ...payload}; | |
| } | |
| return state; | |
| } | |
| const store = createStore(reducer) | |
| function App() { | |
| return ( | |
| <Provider store={store}> | |
| <ConnectedApp /> | |
| <HookedApp /> | |
| </Provider> | |
| ); | |
| } | |
| render(<App />, document.getElementById('root')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment