Suomi Suomi - 1 month ago 10
React JSX Question

Getting a "Uncaught ReferenceError: type is not defined" error in React / Redux?

I'm making a very simple ToDo list with Redux and React. I'm getting a "Uncaught ReferenceError: type is not defined" when trying to add a todo item. I have tried several things, here is my current code. Any ideas what I'm doing wrong? Thank you!

Here is my container:

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addTodo } from '../actions/index';

class Todos extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}

addTodo(e) {
e.preventDefault();
this.props.addTodo(this.state.text);
this.setState({
text: ''
});
}

updateValue(e) {
this.setState({text: e.target.value})
}

render() {
return (
<div>
<form onSubmit={(e) => this.addTodo(e)}>
<input
placeholder="Add Todo"
value={this.state.text}
onChange={(e) => {
this.updateValue(e)
}}
/>
<button type="submit">Add Todo</button>
</form>
<ul>
{ this.props.todo.map((item) => {
return <li key={item.id}>{ item.message }</li>
})}
</ul>
</div>
);
}
}

function mapStateToProps({ todo }) {
return { todo }
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({addTodo}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Todos);


Here is the reducer:

import { ADD_TODO } from '../actions/types';

export default function(state=[], action) {
switch(action.type) {
case ADD_TODO:
return [ action.payload.message, ...state ]
}
return state;
}


And ../reducers/index.js

import { combineReducers } from 'redux';
import TodosReducer from './reducer_addTodo';

const rootReducer = combineReducers({
todo: TodosReducer
});

export default rootReducer;


And the action:

import { ADD_TODO } from './types';
const uid = () => Math.random().toString(34).slice(2);

export function addTodo(message) {
const action = {
id: uid(),
message: message
};
return(
type: ADD_TODO,
payload: action
)
}


When trying to add a Todo item, I get the following error:

Uncaught ReferenceError: type is not defined
at addTodo (bundle.js:21950)
at Object.addTodo (bundle.js:21166)
at Todos.addTodo (bundle.js:23541)
at onSubmit (bundle.js:23562)
at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4532)
at executeDispatch (bundle.js:4332)
at Object.executeDispatchesInOrder (bundle.js:4355)
at executeDispatchesAndRelease (bundle.js:3785)
at executeDispatchesAndReleaseTopLevel (bundle.js:3796)
at Array.forEach (<anonymous>)


EDIT:

Here is the types.js file:

export const ADD_TODO = 'ADD_TODO';

Answer Source

I think the main reason of the error is due to a typo in your addTodo function. Replace the parenthesis with curly braces

export function addTodo(message) {
    const action = {
        id: uid(),
        message: message
    };
    return {
        type: ADD_TODO,
        payload: action
    };
}