Skip to content

Instantly share code, notes, and snippets.

@IPRIT
Last active April 27, 2020 18:50
Show Gist options
  • Select an option

  • Save IPRIT/88ccdf3e207fd1587692583e2d1c13b7 to your computer and use it in GitHub Desktop.

Select an option

Save IPRIT/88ccdf3e207fd1587692583e2d1c13b7 to your computer and use it in GitHub Desktop.
Unstated-next with reducer
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: '',
});
}
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>
);
}
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