Ajay Gaur Ajay Gaur - 14 days ago 8
React JSX Question

On firing action in redux, it says action isn't defined

I am newbie to redux and making a todo list in the redux. My action creator code looks like :

/**
* This file is called Action Creator (creates actions)
*
* Actions are objects as :
* {
* type : 'ADD_TODO' //the only thing needed is type
* text: 'this is our first to do'
* }
*/

module.exports = {

addTodo: function (text) {
return (dispatch) => {
dispatch({type: 'ADD_TODO', data: text});
};
}

};

//export default actions = {
// addTodo(text) {
// return {
// type: 'ADD_TODO',
// text: text
// }
// }
//};
//


Instead of returning object from the action, I am returning a function. So in the store.js file, I've used
thunkMiddleware
from
react-redux
.

My store.js code looks like :

import { applyMiddleware, compose, createStore } from 'redux';
import reducer from '../reducers/reducers';
import thunkMiddleware from 'redux-thunk';

//We separated out the store from the client.js file so that if we have to add middleware here and change our state, we can do that here
//Add middlewares on actions here

let finalCreateStore = compose(
applyMiddleware(thunkMiddleware)
)(createStore);

export default function configureStore(initialState = {todos: []}) {
return finalCreateStore(reducer, initialState);
}


but while firing an action, it says that action is not defined

[Edit]

My Reducer looks like this:

function getId(state) {
return state.todos.reduce((maxId, todo) => {
return Math.max(todo.id, maxId)
}, -1) + 1;
}

export default function reducer(state, actions) {
switch (actions.type) {
case 'ADD_TODO':
Object.assign({}, state, {
todos: [{
//add new to do
text: action.text,
completed: false,
id: getId(state)
}, ...state.todos]
});
break;

default:
return state;
}
}


Also I'm firing actions using
connect
as :

function mapStateToProps(state) {
return state;
}

function mapDispatchToProps(dispatch) {
return {
addTodo: (todo) => {
dispatch(addTodo(todo));
}
}
}

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


I don't have any clue how can I get rid of this error.

Answer

Your reducer signature is (state, actions) but in the function body you have action. You probably meant:

function reducer (state, action) {
   // code
}
Comments