Last active
July 30, 2020 22:39
-
-
Save nij4t/b1731ba955394bcf39d7afd6164dd706 to your computer and use it in GitHub Desktop.
Preact + ReduxZero + TypeScript w/ persistent state
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 { BoundActions } from "redux-zero/types/Actions"; | |
import { Provider, connect } from "redux-zero/preact" | |
import createStore from "redux-zero"; | |
import { h, render, Fragment } from 'preact' | |
interface ConterState { | |
count: number; | |
} | |
export const setCount = (state: ConterState, count: number) => ({ | |
...state, count | |
}) | |
export const actions = () => ({ setCount }) | |
interface ComponentProps { | |
value: string; | |
} | |
interface StoreProps { | |
count: number; | |
} | |
type Props = ComponentProps & StoreProps & BoundActions<ConterState, typeof actions> | |
export const CounterButton = (props: Props) => ( | |
<button onClick={() => props.setCount(props.count + 1)}>{props.value}</button> | |
); | |
export const CounterDisplay = (props: Props) => ( | |
<h1>Count: {props.count}</h1> | |
); | |
const mapToProps = (state: ConterState): StoreProps => ({ count: state.count }); | |
const ConnectedCounterButton = connect( | |
mapToProps, | |
actions | |
)(CounterButton); | |
const ConnectedCounterDisplay = connect( | |
mapToProps, | |
actions | |
)(CounterDisplay); | |
const initialData = JSON.parse(localStorage.getItem("store")) || { count: 0 } | |
const store = createStore(initialData) | |
store.subscribe(() => { | |
localStorage.setItem("store", JSON.stringify(store.getState())) | |
}) | |
const App = () => ( | |
<Provider store={store}> | |
<Fragment> | |
<ConnectedCounterDisplay /> | |
<ConnectedCounterButton value="increment" /> | |
</Fragment> | |
</Provider> | |
); | |
render(<App />, document.body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment