Help with Expense Tracker (step 3 and 7)

Hi, I’m trying to complete the Expense Tracker project, but I ran into a problem. Could someone help me why my editBudget case reducer doesn’t update the state with the new amount from action.payload , and the addTransaction / deleteTransaction case reducer don’t work either.

const budgetsSlice = createSlice({
  name: 'budgets',
  initialState: initialState,
  reducers: {
    editBudget: (state, action) => {
      const index = state.budgets.findIndex((budgetObject) => budgetObject.category === action.payload.category);
      state.budgets[index] = payload;
      return state;
    }
  }
});
const transactionsSlice = createSlice({
  name: 'transactions',
  initialState: initialState,
  reducers: {
    addTransaction: (state, action) => {
      return state.transactions[action.payload.category].push(action.payload);
    },

    deleteTransaction: (state, action) => {
      return state.transactions[action.payload.category].filter(transactionCategory => transactionCategory !== action.payload.category);
    }
  }
});

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-redux/modules/refactoring-with-redux-toolkit/projects/redux-expense-tracker

okay so I figured out where my logic went wrong. I mistakenly though that the state object includes everything, like budgets and transactions properties. I then realized because of the selector function defined at the end of the file, the state keyword only provide access to the budget property. In other words, state gives me an array like this:

[ 
    { category: 'housing', amount: 400 },
    { category: 'food', amount: 100 },
    ...
  ]

so my editBudget case reducer can be written out like so:

editBudget: (state, action) => {
      const index = state.findIndex(obj => obj.category === action.payload.category);
      return state[index] = action.payload;
      }

the transactionsSlice

const transactionsSlice = createSlice({
  name: 'transactions',
  initialState: initialState,
  reducers: {
    addTransaction: (state, action) => {
      state[action.payload.category].push(action.payload);
      return state;
    },

    deleteTransaction: (state, action) => {
      state[action.payload.category].filter(transaction => transaction.id !== action.payload.id);
      return state;
    }
  }
});

of course it can be refactor even more if you’re so inclined :slight_smile:

1 Like