0

I am building a react project and have an initial state

const WalletContext = React.createContext({
  hasExpenses: false,
  wallets: {},
  expenses: [],
  createWallet: () => {},
  addExpense: (data) => {},
});

I am trying to add an expense to wallets. An expense will be an object in itself and when adding the expense I use the id of the wallet to know which wallet to add it to.

Other code has to be updated but what I want is to add an expense to my wallet and update my state. I tried to concat that expense which I have in my action.payload. This is an if statement within my reducer.


if (action.type === 'ADD') {
    const updatedHasExpenses = state.expenses.length > 0;

    state.wallets[action.payload.walletId].concat(action.payload);

    return {
      ...state,
      hasExpenses: updatedHasExpenses,
    };
  }

Problem is that when I try to get this data in one of my other components I have all my wallet ids but each wallet has an empty array associated with it and should not be the case once I add to my wallet with a wallet id an expense.

I am getting the id of the wallet. This I already checked and I am providing to my component the data I have from my context. The issue I believe is coming from my reducer.

My wallets is as follows...

{
 'someId': [{'title': 'sometitle', 'category': 'somecategory' }]
}

My payload is as follows...

{
  id: Math.random().toString(),
  walletId,
  date,
  title,
  category,
  amount,
}
8
  • I think you are mutating the data in your reducer. Instead of directly accessing and concatenating, try using .map . if you can provide the structure of payload and wallets I can think of some logic. ` Commented Oct 12, 2021 at 21:53
  • concat returns a new array but also I can't use map because wallets is an object but not an array Commented Oct 12, 2021 at 21:58
  • Update your question with structure of both payload and wallets so we don't have to guess the structure. Commented Oct 12, 2021 at 21:59
  • My payload is the expense and gets added to my wallets. My wallets is just an object with strings as ids and to each id mapped to an array of expenses Commented Oct 12, 2021 at 22:05
  • You are not assigning the result of concat and the merged array is being discarded Commented Oct 12, 2021 at 22:29

1 Answer 1

0

Try Object.assign instead of concat and add wallets to your return statement:

if (action.type === 'ADD') {
const updatedHasExpenses = state.expenses.length > 0;

const wallets = Object.assign(state.wallets[action.payload.walletId], action.payload)

return {
  ...state,
  hasExpenses: updatedHasExpenses,
  walets: Object.assign(state.wallets, wallets)
};

}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.