I'm trying to figure out why is this not working.
I'm using React with Redux on Typescript.
I have the following code:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {Action} from 'redux';
/** Redux Action **/
class AddTodo implements Action {
type: string;
id: number;
text: string;
constructor(id: number, text: string) {
this.type = 'ADD_TODO';
this.id = id;
this.text = text;
}
}
// ...
class TodoApp extends React.Component {
public render(): JSX.Element {
return (
<div>
<button onClick={() => {
store.dispatch(new AddTodo(0, 'Test'));
}}>
Add Todo
</button>
</div>
);
}
}
// ...
When I click on the button, I'm getting the following error on console:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
I don't understand why is Redux assuming this is an async action or a complex object.
My reducers are not even being executed. They look like this:
const todoReducer: Reducer<Todo> = (state: Todo, action: Action): Todo => {
if (action instanceof AddTodo)
return { id: action.id, text: action.text, completed: false } as Todo;
// ...
else
return state;
};
const todosReducer: Reducer<Todo[]> = (state: Todo[] = [], action: Action): Todo[] => {
if (action instanceof AddTodo)
return [...state, todoReducer(undefined, action)];
// ...
else
return state;
}
If I pass in { type: 'ADD_TODO', id: 0, text: 'Test' }
instead of new Action(0, 'Test')
, then the error is gone, but my action is not correctly executed because of the conditions on the reducer.
Do you know what is going on here?