Last active
April 27, 2020 18:50
-
-
Save IPRIT/88ccdf3e207fd1587692583e2d1c13b7 to your computer and use it in GitHub Desktop.
Unstated-next with reducer
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
| interface IComplexState { | |
| reaction: TReactionType | null, | |
| progress: boolean; | |
| somethingElse: string; | |
| } | |
| type TComplexReducer = Reducer<IComplexState, IAction>; | |
| type TComplexState = [ | |
| ReducerState<TComplexReducer>, | |
| Dispatch<ReducerAction<TComplexReducer>> | |
| ] | |
| function reducer(state: IComplexState, action: IAction): IComplexState { | |
| const { type, payload } = action; | |
| switch (type) { | |
| case EAction.ADD_REACTION: | |
| return { | |
| ...state, | |
| reaction: payload, | |
| }; | |
| } | |
| return state; | |
| } | |
| /** | |
| * Глобальное состояние | |
| */ | |
| export const ComplexState = createContainer<TComplexState>(useComplexState); | |
| function useComplexState(): TComplexState { | |
| return useReducer<TComplexReducer>(reducer, { | |
| reaction: null, | |
| progress: false, | |
| somethingElse: '', | |
| }); | |
| } |
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
| function ExampleComponent(props: IProps) { | |
| const [state, dispatch] = ComplexState.useContainer(); | |
| const onClick = useCallback((reaction: TReactionType) => { | |
| dispatch({ type: EAction.ADD_REACTION, payload: reaction }); | |
| }); | |
| return ( | |
| <button onClick={() => onClick('Haha')}>Test click</button> | |
| ); | |
| } |
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
| function Page() { | |
| return ( | |
| <ComplexState.Provider value={{}}> | |
| <ExampleComponent /> | |
| </ComplexState.Provider> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment