The second section contains functions that manage transactions in the Wasm instance (through the WasmTransactions instance) and the API, as follows:
...
getCategories() {
const categories = this.state.transactions.map(
({ category }) => category
);
// Remove duplicate categories and sort the names in ascending order:
return _.uniq(categories).sort();
},
// Populate global state with the transactions from the API response:
populateTransactions(transactions) {
const sortedTransactions = _.sortBy(transactions, [
'transactionDate',
'id'
]);
this.state.transactions = sortedTransactions;
store.wasm.populateInWasm(sortedTransactions, this.getCategories());
this.recalculateBalances();
},
addTransaction(newTransaction) {
// We need to assign a new ID to the transaction, so this just adds
// 1 to the current maximum transaction ID:
newTransaction.id = _.maxBy(this.state.transactions, 'id').id + 1;
store.wasm.addToWasm(newTransaction);
apiAddTransaction(newTransaction).then(() => {
this.state.transactions.push(newTransaction);
this.hideTransactionModal();
});
},
editTransaction(editedTransaction) {
store.wasm.editInWasm(editedTransaction);
apiEditTransaction(editedTransaction).then(() => {
this.state.transactions = this.state.transactions.map(
transaction => {
if (transaction.id === editedTransaction.id) {
return editedTransaction;
}
return transaction;
}
);
this.hideTransactionModal();
});
},
removeTransaction(transaction) {
const transactionId = transaction.id;
store.wasm.removeFromWasm(transactionId);
// We're passing the whole transaction record into the API call
// for the sake of consistency:
apiRemoveTransaction(transaction).then(() => {
this.state.transactions = this.state.transactions.filter(
({ id }) => id !== transactionId
);
this.hideTransactionModal();
});
},
...
The populateTransactions() function fetches all of the transactions from the API and loads them into the global state and the Wasm instance. The category names are extrapolated from the transactions array in the getCategories() function. The results are passed to the WasmTransactions instance when store.wasm.populateInWasm() is called.
The addTransaction(), editTransaction(), and removeTransaction() functions perform the actions that correspond with their names. All three functions manipulate the Wasm instance and update the data on the API through a fetch call. Each of the functions call this.hideTransactionModal() because changes to a transaction can only be made through the TransactionModal component. Once the change is successfully made, the modal should close. Let's look at the TransactionModal management code next.