Created
January 23, 2021 02:12
-
-
Save brentsowers1/b9d10c09dfadbcbc1621764203f994dd 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
import React from 'react'; | |
import globalHook from 'use-global-hook'; | |
// You'd probably want to put this and useCounter in a separate file, and only | |
// export useCounter | |
const globalCounterActions = { | |
setValue: (store, newValue) => { | |
store.setState({ value: newValue }); | |
}, | |
}; | |
const useCounter = globalHook(React, { value: 0 }, globalCounterActions); | |
const globalLoggedInUserActions = { | |
setUsername: (store, newValue) => { | |
store.setState({ username: newValue }); | |
}, | |
}; | |
const useLoggedInUser = globalHook(React, { username: '' }, globalLoggedInUserActions); | |
const GlobalHookExample = () => { | |
return ( | |
<div> | |
Main app container | |
<CounterDisplay /> | |
<CounterDisplay /> | |
<CounterIncrementer /> | |
<LoggedInUserDisplay /> | |
<LoggedInUserDisplay /> | |
<LoggedInUserSetter /> | |
</div> | |
); | |
}; | |
const CounterIncrementer = () => { | |
const [counter, counterActions] = useCounter(); | |
return ( | |
<div> | |
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label,react/button-has-type */} | |
Increment counter - <button onClick={() => counterActions.setValue(counter.value + 1)} /> | |
</div> | |
); | |
}; | |
const CounterDisplay = () => { | |
const [counter] = useCounter(); | |
return <div>Counter value = {counter.value}</div>; | |
}; | |
const LoggedInUserSetter = () => { | |
const loggedInUserActions = useLoggedInUser()[1]; | |
return ( | |
<div> | |
Set logged in user name - | |
<input type="text" onChange={event => loggedInUserActions.setUsername(event.target.value)} /> | |
</div> | |
); | |
}; | |
const LoggedInUserDisplay = () => { | |
const [user] = useLoggedInUser(); | |
return <div>Logged in user value = {user.username}</div>; | |
}; | |
export default GlobalHookExample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment