Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda