I intend to create a simple counter using react redux in typescript.
I have defined my store with actions and reducers in the following manner but not sure how to invoke dispatch with a specific action
import * as React from 'react';
import { createStore, Action, Reducer } from 'redux';
export interface CounterState {
counter: number;
}
export enum ActionTypes {
INCREMENT = 'increment',
DECREMENT = 'decrement'
}
export interface IncAction { type: ActionTypes.INCREMENT }
export interface DecAction { type: ActionTypes.DECREMENT }
export type CounterAction = IncAction | DecAction;
const reducer: Reducer<CounterState> = (state: CounterState = {counter: 0}, action: CounterAction) => {
switch (action.type) {
case ActionTypes.INCREMENT:
return { ...state, counter: state.counter + 1};
case ActionTypes.DECREMENT:
return { ...state, counter: state.counter - 1};
default:
return state;
}
};
let store = createStore(reducer, { counter: 0 });
Following is how my react component Counter
looks like
interface IProps {}
interface IState {}
export default class Counter extends React.Component<IProps, IState> {
private unsubscribe: Function;
constructor(props: IProps, context?: any) {
super(props, context);
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => this.render());
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { counter } = store.getState();
return (
<div>
<p>
<label>Counter: </label><b>#{counter}</b>
</p>
<button onClick={e => store.dispatch('increment') }>+</button>
<span style={{ padding: "0 5px" }} />
<button onClick={e => store.dispatch('decrement') }>-</button>
</div>
);
}
}
I am getting following error -
ERROR in [at-loader] ./src/components/Counter.tsx:63:54 TS2345: Argument of type '"increment"' is not assignable to parameter of type 'AnyAction'.
ERROR in [at-loader] ./src/components/Counter.tsx:65:54 TS2345: Argument of type '"decrement"' is not assignable to parameter of type 'AnyAction'.