Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
How to update an array in an object in Javascript

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,
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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)
};

}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!