Created
July 2, 2020 14:51
-
-
Save CKGrafico/a58ec49e40a6b466a2bce224b7059edf to your computer and use it in GitHub Desktop.
Example Frontend Boilerplates Store
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 { useExampleStore, ExampleStoreType } from '~/store'; | |
export function useExample() { | |
// You can use stores directly form components, this is only an example of hook | |
const [state, dispatch] = useExampleStore(); | |
function incrementProperty1() { | |
dispatch({ | |
type: ExampleStoreType.ADD_TO_FIRST, | |
payload: 10 | |
}); | |
} | |
return [state, incrementProperty1] as const; | |
} |
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
// More info https://github.com/CKGrafico/Frontend-Boilerplates/tree/react | |
import { createStore, ReducerType, useStore } from 'react-hookstore'; | |
import { GenericPayload } from '~/app/core'; | |
const name = 'ROOT/EXAMPLE'; | |
enum Type { | |
ADD_TO_FIRST = 'ROOT/EXAMPLE/ADD_TO_FIRST', | |
ADD_TO_SECOND = 'ROOT/EXAMPLE/ADD_TO_SECOND' | |
} | |
type Payload = GenericPayload<Type>; | |
interface State { | |
property1: number; | |
property2: number; | |
} | |
const state: State = { | |
property1: 0, | |
property2: 1 | |
}; | |
const reducers: ReducerType<State, Payload> = function (state: State, { type, payload }) { | |
switch (type) { | |
case Type.ADD_TO_FIRST: | |
return { ...state, property1: state.property1 + payload }; | |
case Type.ADD_TO_SECOND: | |
return { ...state, property1: state.property2 + payload }; | |
default: | |
return { ...state }; | |
} | |
}; | |
const store = createStore<State>(name, state, reducers); | |
export const ExampleStoreType = Type; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment