Created
July 21, 2019 06:53
-
-
Save chathuranga94/f84c2b83c7a191e05b8ba71c97f4c80f to your computer and use it in GitHub Desktop.
Global State
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 { globalStore } from './global'; | |
const languages = { en: 'en', fr: 'fr' }; | |
const { Provider: AppProvider, Consumer: AppConsumer } = React.createContext({}); | |
const App = () => { | |
const init = { lang: 'en', color: 'blue', count: 20 } | |
return ( | |
<AppProvider value={globalStore(init)}> | |
<LanguagePicker /> | |
<Menu /> | |
</AppProvider> | |
); | |
} | |
const Menu = () => | |
<div> | |
<Lang /> | |
<Color /> | |
<Default /> | |
</div>; | |
const LanguagePicker = () => | |
<AppConsumer> | |
{store => | |
<div> | |
<button onClick={() => store.set('lang', languages.en)}>English</button> | |
<button onClick={() => store.set('lang', languages.fr)}>French</button> | |
</div> | |
} | |
</AppConsumer> | |
const Lang = () => | |
<AppConsumer> | |
{store => <p>Locale: {store.get('lang')}</p> } | |
</AppConsumer> | |
const Color = () => | |
<AppConsumer> | |
{store => <p>Color: {store.get('color')}</p>} | |
</AppConsumer> | |
const Default = () =><p>Not a consumer</p>; | |
export default App; |
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, { useState, useContext, useReducer } from 'react'; | |
export const globalStore = (init) => { | |
const store = {}; | |
Object.entries(init).forEach(prop => { | |
const [key, value] = prop; | |
const hook = useState(value); | |
store[key] = { get: hook[0], set: hook[1] } | |
}); | |
const get = (path) => store[path].get; | |
const set = (path, value) => store[path].set(value); | |
// const init = () => { } | |
return { get, set } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment