I am having an issue mapping some JSON:
https://environment.data.gov.uk/flood-monitoring/id/floodAreas/?county=Lincolnshire
Would really appreciate the help, thanks
I am using the following code to attempt to map the json object
await fetch('https://environment.data.gov.uk/flood-monitoring/id/floodAreas/?county=Lincolnshire')
.then(res => res.json())
.then(json => {
this.setState({
hasLoaded: true,
weatherItems: json
})
});
static renderFloodTable(weatherItems) {
return (
<table class="centerTable" className='table table-striped' aria-labelledby="tabelLabel">
<thead>
<tr>
<th>County. (C)</th>
</tr>
</thead>
<tbody>
{weatherItems.items.map(item =>
<tr key={item.fwdCode}>
<td>{item.fwdCode}</td>
</tr>
)}
</tbody>
</table>
);
}
i think the rendering in calling too soon so the weatherItems is'nt set yet. try this:
{weatherItems ? weatherItems.items.map( // ... etc... // ) : null}
and btw, you should not use await And .then toogether... choose one...
Related
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"
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>
Still following the following tutorial:
https://www.techiediaries.com/php-react-rest-api-crud-tutorial/
I am finally getting no errors in the console. But I am getting nothing but a blank array in the console that simply reads [ ]
The complete code is as follows:
<script type="text/babel">
class App extends React.Component {
componentDidMount() {
const url = 'api/testQuery.php'
axios.get(url).then(response => response.data)
.then((data) => {
this.setState({ users: data })
console.log(this.info.users)
})
}
info = {
users: []
}
render() {
return (
<React.Fragment>
<h1>All Users</h1>
<table border='1' width='100%'>
<tr>
<th>Username</th>
<th>Fullname</th>
<th>Email</th>
</tr>
{this.info.users.map((user) => (
<tr>
<td>{ user.username }</td>
<td>{ user.fullname }</td>
<td>{ user.email }</td>
</tr>
))}
</table>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
The json that is being returned from the testQuery.php script looks like this:
[
{
"uid":"7",
"username":"tna.mjordan",
"fullname":"Michael Jordan",
"email":"tna.mjordan#tna.com",
"userlevel":"9",
"division":"Chicago"
},
// and so on
]
Any thoughts as to why I am getting a blank users array, and how to fix it?
I think you need to print the info from the state, not the attribute itself. Same happens in the returned renderized HTML. Besides, the setState should modify the info attribute, not the users property within. Below you can find your code with the changes applied:
class App extends React.Component {
componentDidMount() {
const url = "api/testQuery.php";
axios
.get(url)
.then((response) => data)
.then((data) => {
this.setState({ info: { users: data } });
console.log(this.state.info.users);
});
}
info = {
users: [],
};
render() {
return (
<React.Fragment>
<h1>All Users</h1>
<table border="1" width="100%">
<tr>
<th>Username</th>
<th>Fullname</th>
<th>Email</th>
</tr>
{this.state.info.users.map((user) => (
<tr>
<td>{user.username}</td>
<td>{user.fullname}</td>
<td>{user.email}</td>
</tr>
))}
</table>
</React.Fragment>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
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>
))
I'm using React to sort table using underscore.js, but the sorted data is added to the bottom of the table along with the original data. I need to just render the sorted table in my component. What is the correct way to achieve this?
class Players extends React.Component {
constructor() {
super();
this.state = { players:[]};
}
componentDidMount() {
fetch('http://localhost:5000/players')
.then((data) => data.json())
.then((data) => this.setState( { players: data } ));
}
sortByCode = () => {
this.setState( { "players": _.sortBy(this.state.players,'TEAMCODE')});
}
render() {
return (
<table border={1}>
<tbody>
<tr>
<th onClick={this.sortByCode}>Code</th>
<th>Name</th>
</tr>
{this.state.players.map( (item) => {
return
<tr key={item.TEAMCODE}>
<td><img height={20} width ={20}
alt="pics" src={'/logos/' + item.TEAMCODE + '_logo.svg'}></img>
</td>
<td>{item.TEAMCODE}</td>
<td>{item.NAME}</td></tr>;
})}
</tbody>
</table>
)};
It's not recommended to use the index as a key (see ReactJS documentation)
I would advise to find the unique key of your dataset that seems to be the combination of TEAMCODE and NAME so you should replace your code with :
<tr key={item.TEAMCODE+item.NAME}>