1

I've created a simple Budget app using React. The user can add Income/Expense Description and Value by filling out the inputs and the final result gets added to the Expenses/Incomes lists.

I managed to add the Income/Expenses values (numbers): I've created a setState with incomes: [1, 3, 4], map around the income array and print out the values by updating the state.

I can't understand how to add the description. I've checked some questions here on Stack but they only use setState and creating a state for each element (incomes, incomeValues, expenses, expensesValue), which is not what I want.

Is there a way to do this without involving too many states? Maybe using an Object?

Github Link

3
  • so you want to have a key-value pair instead of the integers in the 'incomes' array? Commented Mar 14, 2019 at 21:43
  • Sure, you can have an array of objects. It's really up to you how you want to model your data, is not a single right way. Commented Mar 14, 2019 at 21:43
  • I've used <Income description={description} key={i} income={income} />...but of course description is returned undefined. So I should be doing something like this? setState() { incomes: {value: [2,333,29], description: ['Number one', 'Number Two', 'Three']} } Commented Mar 14, 2019 at 21:45

1 Answer 1

3

Your state is an object

{
  monthlyBudget: 0,
  incomesSum: 0,
  expensesSum: 0,
  incomes: [0],
  expenses: [0]
}

What you could do instead of adding more numbers to the incomes array is add objects to the incomes array. Exactly like you guessed.

{
  monthlyBudget: 0,
  incomesSum: 0,
  expensesSum: 0,
  incomes: [
    { amount: 0, description: 'some description' },
    { amount: 1, description: 'second description' },
  ]
  expenses: [0]
}

in which case you would still use map to access the properties of the object.

this.sate.incomes.map(income => {
  // do something with income.amount
  // do something with income.description
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.