Reputation: 61
I'm just starting with react redux with Typescript (v 2.6.1) and I have been working on a little app from the VS 2017 boilerplate. At my fifth View, I see that for some reason I have problems in creating actions. Basically in the code below that is a very simplified code, that should work very easily, if I remove the multiplier in the Multiply action works but when I add the multiplier doesn't. I can't figure it out.
Trying to simplify and fix it, I see that it's not even working the following code, which should be pretty straighforward.
import { AppThunkAction } from "ClientApp/store";
import { Action, Reducer } from 'redux';
import { fetch, addTask } from 'domain-task';
import update from 'immutability-helper';
// The top-level state object
export interface CompoundState {
value: number,
}
export interface AddAction {
type: 'ADD_ACTION',
addend:number
}
export interface MultiplyAction {
type: 'MULTIPLY_ACTION',
multiplier:number
}
type KnownAction = AddAction | MultiplyAction
export const actionCreators = {
add: (addend): AppThunkAction<AddAction> => (dispatch, getState) => {
dispatch({ type: 'ADD_ACTION', addend: addend })
},
multiply: (multiplier): AppThunkAction<MultiplyAction> => (dispatch, getState) => {
dispatch({ type: 'MULTIPLY_ACTION', multiplier: multiplier })
},
}
const unloadedState: CompoundState =
{
value: 0,
};
export const reducer: Reducer<CompoundState> = (state: CompoundState, action: KnownAction) => {
switch (action.type) {
case 'ADD_ACTION':
return update(state, {
value: {
$set: state.value + action.addend
}
});
case 'MULTIPLY_ACTION':
return update(state, {
value: {
$set: state.value * action.multiplier
}
});
}
return state || unloadedState;
};
What do you think?
Upvotes: 1
Views: 4885
Reputation: 61
export const reducer: Reducer<CompoundState> = (state: CompoundState, incomingAction: Action) => {
const action = incomingAction as KnownAction;
switch (action.type) {
case 'ADD_ACTION':
return update(state, {
value: {
$set: state.value +1
}
});
case 'MULTIPLY_ACTION':
return update(state, {
value: {
$set: state.value * 2
}
});
}
return state || unloadedState;
};
Hope it can help somebody.
Upvotes: 4