I'm having trouble displaying data from my firebase database into a table using React. How would I map through a transaction consisting of: payee, amount, date, category onto a table? So when the user enters a transaction, it is mapped onto the table. For example, when entering a transaction
const transaction = {
payee: Wal-mart,
date: 01-29-2022,
category: groceries,
amount: 120,
From Account: Checking
I'm trying to use Semantic UI to build a table so when a transaction is entered it will populate into a table for viewing. I tried building the table body but it wont allow me to map through each transaction value as a row. Is there a more efficient way of dynamically entering this into a table or a framework that can make this more simple?
import AddTransaction from "./AddTransaction";
import { useCollection } from "../../hooks/useCollection";
//styles
import "./Transactions.css";
import { Table } from "semantic-ui-react";
export default function Transactions() {
const { documents, error } = useCollection("transactions");
return (
<div className='transactions'>
<div className='transaction-title'>
<h1>Transactions</h1>
</div>
<AddTransaction />
<div className='transactions-list'>
{error && <p className='error'>{error}</p>}
{documents && (
<>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Payee</Table.HeaderCell>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Category</Table.HeaderCell>
<Table.HeaderCell>Amount</Table.HeaderCell>
<Table.HeaderCell>Notes</Table.HeaderCell>
<Table.HeaderCell>From Account</Table.HeaderCell>
</Table.Row>
<Table.Body>
<Table.Row>
{documents.map((doc) => (
<>
<Table.Cell>{doc.transaction}</Table.Cell>
<Table.Cell>{doc.date}</Table.Cell>
<Table.Cell>{doc.amount}</Table.Cell>
</>
))}
</Table.Row>
</Table.Body>
</Table.Header>
</Table>
</>
)}
</div>
</div>
);
}
You didn't specify which error you're running into, so it's possible I've missed something, but here are the issues I've noticed:
Based on what you wrote above, I'm assuming each transaction maps to a single document with the fields date
, payee
, etc at the root level. Assuming that's the case, there is no transaction
field so (<Table.Cell>{doc.transaction}</Table.Cell>
) doesn't make sense.
Even if there were a transaction object on doc, you're trying to output an object directly to the DOM
(<Table.Cell>{doc.transaction}</Table.Cell>
). Objects aren't valid children in React, so that will throw an error.
You're trying to use the document directly, but you need to access its data via the data()
method that Firebase includes on each doc. doc
also has other information on it like id
and createTime
, hence needing to use the data()
method to get your data.
You're looking for something like this:
<Table.Row>
{documents.map((doc) => (
<>
<Table.Cell>{doc.data().date}</Table.Cell>
<Table.Cell>{doc.data().payee}</Table.Cell>
<Table.Cell>{doc.data().category}</Table.Cell>
<Table.Cell>{doc.data().amount}</Table.Cell>
</>
))}
</Table.Row>