Reputation: 95
I am new to Redux, and reading through the documentation while I try to make a basic to do list.
I can't seem to get my reducer to add an item to the list. The correct action creator is firing, I think there is perhaps something in my Object.assign
statement that I am not understanding. Below is my store.js
file.
const defaultState = {
todos:[
{
text: 'walk gilbert'
},
{
text: 'cook dinner'
},
{
text: 'clean bathroom'
}
]
}
function todos(state = defaultState) {
return state;
}
function modifyList(state = defaultState, action) {
switch(action.type) {
case 'ADD_TODO':
return Object.assign({}, state, {
todos: [
...state.todos,
{
text: action.text,
}
]
})
default:
return state;
}
}
const rootReducer = combineReducers({todos, modifyList})
const store = createStore(rootReducer, defaultState);
export default store;
Thanks!
Upvotes: 3
Views: 15838
Reputation: 67627
Looks like you're a bit confused about how combineReducers
works.
The combineReducers
utility is intended to both define the fields or "slices" in your state tree object, and also delegate the work of updating those slices to specific functions. In your case, it looks like you really just want to have a state.todos
slice, but the way you're calling combineReducers()
is actually creating state.todos
and state.modifyList
. In addition, when you use combineReducers
, each slice reducer only ever sees its one piece of the overall state tree. In other words, inside of the todos()
reducer, the state
parameter is just the todos
section.
So, what you want is something more like this:
const defaultTodosState = [
{text : 'walk gilbert'},
{text : "cook dinner"},
{text : "clean bathroom"}
];
function todos(state = defaultTodosState, action) {
switch(action.type) {
case 'ADD_TODO': {
return [
...state,
{text: action.text}
]
}
default:
return state;
}
}
const rootReducer = combineReducers({todos});
You might want to read through the sections of the Redux docs that discuss combineReducers
and reducers in general: Introduction - Core Concepts, Basics - Reducers, API Reference - combineReducers
, and Structuring Reducers - Using combineReducers
.
Upvotes: 6