I am working on transactions table. I just want to add, remove and update the transactions in the table.
I have a 'Transactions.js' functional component which has the state of transactions (using hooks) and I also have a 'TransactionsForm.js' component which receives 'setTransactions' function as a prop from 'Transactions.js' to add or update the transactions state
Transactions.js
const [transactions, setTransactions] = useReducer(
transactionsReducer,
fetchTransactions()
)
TransactionsForm.js
const [values, setValues] = useState({
description: '',
transactionType: '',
date: '',
category: '',
amount: ''
})
const handleChange = event => {
const { name, value } = event.target
setValues({ ...values, [name]: value })
}
const handleAdd = () => {
setTransactions({
type: 'add',
transactionType: 'income',
description: values.description,
date: values.date,
category: values.category,
amount: values.amount
})
}
const handleUpdate = () => {
setTransactions({
type: 'update',
id: 1,
transactionType: 'income',
description: values.description,
date: values.date,
category: values.category,
amount: values.amount
})
}
const handleSubmit = event => {
event.preventDefault()
// 1. handleUpdate() if the user is updating an existing transaction
// 2. handleAdd() if the user is adding new transaction
}
As you can see I have both functions, handleAdd and handleUpdate. but I need to call one of them according to the user's action (update or add) and also if it is update, I need to get transaction id.
What is the best way to accomplish this? I know that I shouldn't create two separate forms for add and update