I am working on the Refactoring with Redux Toolkit chapter and am stuck and confused on the Expense Tracker project.
I am trying to do the first half of the project to refactor the budget slice, but I get the error:
Uncaught Error: Reducer “budgets” returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don’t want to set a value for this reducer, you can use null instead of undefined.
What I am confused about is that the project uses configureStore() and I thought that you did not need to have a default case for the reducer, but this error seems to be saying otherwise?
Your initialState has the keys ‘category’ and ‘amount’ but no key ‘budget’. You need to add that in the initalState object. Just add the key in the map method and initialize it with null.
Or if you just want have an object with these two keys as the initial state, remove the key from the reducer:
Yes, ‘budgets’ is still undefined.
You have the initialState which you reference with ‘state’. That is an array containing many objects. These objects have keys called ‘budget’.
What exactly do you want selectBudgets to return?
Yes, but what is ‘budgets’? There is no object ‘budgets’ yet.
There are several ‘budget’ values inside the objects in the array. If you want to return just one of those values, you should initialize your initialState to an object instead of an array. If you just want to return the array you can do that by simply returning ‘state’:
export const selectBudgets = (state) => state // returning the array
Yes. thanks very much! Once I got past that typo error, I figured out what you were meaning.
The state in reducer is budgets so instead of “state.budgets,” I needed to just use “state.”
I had another look at the project. Yes, you should use state.filter instead of state.budgets.filter as there is no object 'budgets" in the initial state you can access within createSlice. But when exporting you were right: You should export it as state.budgets because createSlice returns the state as an object named as the slice’s name.