Populating Firestore database data into a table modular version 9 - javascript

I am trying to read Database Data into a Table but I am getting an empty table from my Output though I am convinced I am doing the right thing.
Below is My code in the useEffect Hook and how I am Calling the data in the Table data jsx element.
Intervening for your Help
My Use useEffect Code
useEffect(() => {
const readCustomersData= async() =>{
const data = await getDocs(customersCollectionRef);
setCustomers(data.docs.map((doc) => ({ ...doc.data(), id:doc.id})));
}
readCustomersData();
},[])
How I am Calling The code in The jsx Elememnt
{ customers.map(( value, index) => {
return(
<tr key={index.id}>
<th scope="row">{index+1}</th>
<td>{value.cname}</td>
<td>{value.contact}</td>
<td>{}</td>
<th>{}</th>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td className='p-2 d-flex justify-content-space-between'>
<Button variant='success'>Update</Button> <Button variant='danger'>Delete</Button>
</td>
</tr>
)
})}
</tbody>

Related

Is there a way I can conditionally render a value in a table if it is not undefined?

I am currently trying to develop a table dashboard for a list of properties for the owner to see. And the issue that I'm having is that when I'm trying to display the tenant information, some of the properties don't have tenants(the data called rentalInfo in the JSON is "undefined") and I'm trying to conditionally render when the property does have a tenant, only then I display the tenant's name.
Here's the code for my Table:
import './table.css'
export default function Table(props){
const properties = props.data;
console.log(properties[4].rentalInfo[0].tenant_first_name,typeof(properties[4].rentalInfo[0].tenant_first_name))
const fourth_tenant = properties[4].rentalInfo[0].tenant_first_name
const rows = properties.map((row, index)=>{
return(
<tr>
<th>{row.rentalInfo.tenant_first_name !== 'undefined'?fourth_tenant:"No tenant at the moment"}</th>
</tr>
)
})
return(
<div>
<table>
<thead>
<tr>
<th>Tenant</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
)
}
Here's the code where I call the Table Function along with my Axios.get call
export default function OwnerDashboard2(){
const [dataTable, setDataTable] = useState([]);
useEffect(() => {
axios.get("https://t00axvabvb.execute-api.us-west-1.amazonaws.com/dev/propertiesOwner?owner_id=100-000003")
.then(res => {setDataTable(res.data.result)})
.catch(err => console.log(err))
}, []);
return(
<div className="OwnerDashboard2">
<Row>
<Col xs={2}><Navbar/></Col>
<Col>{dataTable.length!==0 && <Table data ={dataTable}/>}</Col>
</Row>
</div>
)
}
I tried using <th>{row.rentalInfo.tenant_first_name !== 'undefined'?fourth_tenant:"No tenant at the moment"}</th> but the issue is it's still displaying the only tenant in all the properties(fourth_tenant) for each column.
you can use !! to convert the value to boolean type
just like this:
!!row.rentalInfo.tenant_first_name ? row.rentalInfo.tenant_first_name : "tenant is undefined"

How to dynamically render jsx with objects values

Data is an array object. I want to render table columns dynamically according to data object. I used this same technique to generate table head its working. Is there any way to fix this issue?
const DataTable = ({data, deleteHandler, loading, tableFields}) => {
const thead = [];
const tbody = [];
const [values, setValues] = useState({});
for (const [key, value] of Object.entries(tableFields)) {
thead.push(<td>{value}</td>);
}
data.map((field) => {
for(const[key,value] of Object.entries(field)){
tbody.push(
<tr>
<td>{value}</td>
</tr>
);
}
})
return (
<Fragment>
<Card className={classes.__bk_admin_card}>
<Table borderless hover className={classes.__bk_admin_table}>
<thead>
<tr>
{thead}
</tr>
</thead>
<tbody>
{tbody}
</tbody>
</Table>
</Card>
</Fragment>
)
}

Position ranking table in react js

i'm creating a web app in Reactjs with a ranking table all managed by firebase, but i came across a doubt:
after sorting the table based on who wagered the most money with the 'order by' command, I wish I could be able to change the position number, for example if it was second it becomes first (from 2 to 1).
That's my screen:
That's my code:
import React, {useState, useEffect} from 'react'
import './Table.css'
import {firebase} from '../../firebase'
function Table() {
const [peopleShow, setPeopleShow] = useState([]);
const ref = firebase.firestore().collection("Lista");
console.log(ref);
function getData(){
ref
.orderBy("money", "desc")
.onSnapshot((querySnapshot) => {
const items = [];
querySnapshot.forEach((doc) => {
items.push(doc.data());
});
setPeopleShow(items);
})
}
useEffect(() => {
getData();
}, [])
return (
<section>
<div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
{peopleShow.map((val) => {
return(
<tr key={val.ID}>
<td>{val.ID}</td>
<td>{val.nationality}</td>
<td>{val.username}</td>
<td>{val.money} $ <i class="far fa-caret-up"></i></td>
<td>{val.lastbid}</td>
<td>{val.newbid} $</td>
</tr>
)
})}
</tbody>
</table>
</div>
</section>
)}
export default Table
so i was wondering to solve this doubt, should i do a bubble sort? I state that the positions of the table I had defined momentarily with the id of my database. Thanks to all!!
You can use the index in the map function instead of making the number dependant on the data.
{peopleShow.map((val, index) => {
return(
<tr key={val.ID}>
<td>{index + 1}</td>
<td>{val.nationality}</td>
<td>{val.username}</td>
<td>{val.money} $ <i class="far fa-caret-up"></i></td>
<td>{val.lastbid}</td>
<td>{val.newbid} $</td>
</tr>
)
})}

How to filter through a table with React?

I am trying to filter through an array so that when a certain tab is clicked, only those results show. I have managed to isolate the certain variables I want to remain but the others that don't fit the criteria still remain. How do I get the filter method to actually render on the page so that the results can be shown. I have searched for hours for and have tried to get the tbody and sort through that but I just get confused as I am mostly new to javascript and react. Can someone point me in the right direction?
Filter Method
const tbody = document.getElementsByTagName('tbody')
console.log(tbody)
//change active class
function addTabBackground() {
const tabs = document.querySelectorAll('[data-tab]')
window.onload = function () {
tabs.forEach(tab => {
tab.addEventListener('click', () => {
if (tab.getAttribute('data-tab') === 'gains') {
listOfOptions.map(option => {
console.log(option.totalProfit)
})
}
tabs.forEach(tab => {
tab.classList.remove('active')
})
tab.classList.add('active')
})
})
}
}
<div className="outputs" >
<table>
<thead>
<tr>
<th>Date</th>
<th>Stock Name</th>
<th>Price Of Option</th>
<th>Number Of Options</th>
<th>Total Amount Spent</th>
<th>Option Sold At</th>
<th>Amount Of Options Sold</th>
<th>Proft</th>
</tr>
</thead>
{listOfOptions.map(option => {
return (
<tbody>
<tr>
<td>{option.clock}</td>
<td>{option.name.toUpperCase()}</td>
<td>${option.price}</td>
<td>{option.amountOfOptions}</td>
<td>${option.totalAmountSpent.toFixed(2)}</td>
<td>${option.optionPriceSoldAt}</td>
<td>{option.amountOfOptionsSold}</td>
<td style={{ color: option.totalProfit >= 0 ? 'green' : 'red' }}>${option.totalProfit.toFixed(2)}</td>
</tr>
</tbody>
)
})}
</table>
</div>
I have used React-Bootstrap-v5 to get Nav, Nav.Item with eventKey and then passed selectedKey in its onSelect function to change the tabs.
Then once we get the data inside my data variable, I used the map function to go over the array. Inside Map Function I have used the required condition to filter the elements i.e. variable = 'Open' or 'Live'.
This will only show the Open type in Open Tab and Live Type Data inside Live Tab.
Hope it's clear to you.
import React, { useEffect, useState } from 'react';
const TestSeries = () => {
// Declare Variable for data to be fetched from API
const [data, setData] = useState([]);
const fetchTestData = async () => {
const response = await axios.get(site_ip + '/apiLink');
setData(response.data.Content);
};
useEffect(() => {
fetchTestData();
}, []);
// State Variable to keep track of active tab
const [activeTab, setActiveTab] = useState('Open');
return (
<>
<Nav
activeKey={activeTab}
fill
variant="pills"
onSelect={(selectedKey) => {
setActiveTab(selectedKey);
}}
>
<Nav.Item>
<Nav.Link eventKey="Open">Open</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="Live">Live</Nav.Link>
</Nav.Item>
</Nav>
<br />
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Column1</th>
<th>Column2</th
<th>Column3</th>
<th>Column4</th>
<th>Data Type</th>
</tr>
</thead>
<tbody>
{data.map((item, index) =>
// Condition by which data will be filtered
item.data_type == activeTab ? (
<tr>
<td>{index + 1}</td>
<td>{item.col1}</td>
<td>{item.col2}</td>
<td>{item.col3} </td>
<td>{item.col4}</td>
<td>{item.data_type}</td>
</tr>
) : null
)}
</tbody>
</Table>
</>
);
};
export default TestSeries;
Result
Assuming from the comment that you have something vaguely looking like:
function Page() {
return (
<>
<Navbar />
<Table />
</>
)
}
What you need to do is to store the current tab in a state, and pass this state down to the Table component so that you can use a Array.filter when rendering your table.
function Page() {
const [activeTab, setActiveTab] = useState(DEFAULT_ACTIVE_TAB)
return (
<>
<Navbar activeTab={activeTab} setActiveTab={setActiveTab} />
<Table activeTab={activeTab} />
</>
)
}
Your Navbar component should have a onClick handler where it is calling the setActiveTab function when the active tab change.
Then in your Table component you should have something like this:
function Table({ activeTab }) {
return (
<table>
...
{listOfOptions
.filter(option => /* something depending on the activeTab */)
.map(option => <... />)
}
</table>
}

Display JSON child content to HTML table in Reactjs

Guys i know this already asked many times, but i still don't get how to solve my problem. So what i want to do is display some nested JSON data to HTML table.
So this is the JSON i fetch.
and this is my reactjs code:
var [infectionData, setInfectionData] = useState({
response: []
});
var [isLoaded, setLoaded] = useState(false);
useEffect(() => {
var fetchData = async () => {
var url = "https://api.covid19api.com/summary";
var result = await axios.get(url);
var response = result.data
response = Array(response);
setInfectionData({ response: response });
console.log(infectionData.response);
}
fetchData();
setLoaded(true);
});
and this is the HTML table:
<Table bordered hover className="mt-3 w-75">
<thead>
<tr>
<th>Country</th>
<th>Total Infection</th>
<th>New Deaths</th>
</tr>
</thead>
<tbody>
{
infectionData.response.Countries.map((item) => (
<tr>
<td>{item.Country}</td>
<td>{item.TotalConfirmed}</td>
<td>{item.NewDeaths}</td>
</tr>
))
}
</tbody>
</Table>
Any idea how to solve this ?
Here are the Array constructor https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array
response = Array(response); remove this line and everything will be good.
Or
infectionData.response[0].Countries.map((item) => (
<tr>
<td>{item.Country}</td>
<td>{item.TotalConfirmed}</td>
<td>{item.NewDeaths}</td>
</tr>
))
You may try with this
infectionData.response.Countries && infectionData.response[0].Countries.map((item) => (
<tr>
<td>{item.Country}</td>
<td>{item.TotalConfirmed}</td>
<td>{item.NewDeaths}</td>
</tr>
))

Categories