Reputation: 193
I am trying to calculate the array and show the number on the dashboard. I tried to fetch('data/users.json)
but got an error that shows 0.
Need to calculate the id from two JSON files located at public folder inside data folder, you can see on the code below.
import React from 'react'
import '../Navbar/navbar.css'
import '../Dashboard/dashboard.css'
// import UserList from "./data/users.json"
const Dashboard = () => {
return (
<div>
<main>
<h1 className= "heading">Welcome to Dashboard</h1>
{/* <p> User data list : {Object.keys(UserData).length}</p>
<p>Suscriber list: {Object.keys(Suscriber).length}</p> */}
<p>
Lorem
ipsum dolor sit, amet consectetur adipisicing elit. Placeat accusantium
rerum dolorem odio amet id blanditiis nobis incidunt consequuntur
molestiae doloribus corrupti quidem dolor ex, assumenda beatae dolore?
Voluptatem, ab?Lorem ipsum dolor sit amet consectetur, adipisicing elit.
</p>
<div className="users_view">
<div className="flexs">
<div className="total_users">
<h1>Total Users: {Object.keys(fetch('data/users.json')).length} </h1>
</div>
</div>
<div className="flexs">
<div className="total_users">
<h1>Subscribed user: {Object.keys(fetch('data/subscriptions.json')).length}</h1>
</div>
</div>
</div>
</main>
</div>
)
}
export default Dashboard
Below image is of directories:
Anyone help me to fetch those 2 JSON data and calculate the array number to display on the dashboard.
Below images show the output:
Upvotes: 2
Views: 5017
Reputation: 2129
This is how I'd advice to import a json file:
import React from 'react'
export default function App() {
const [users,setUsers] = React.useState([{}])
React.useEffect(()=>{
fetch('data/users.json').then((res)=>res.json()).then((data)=>{
setUsers(data)
})
},[])
return (
<div className="App">
<h1>Users:{users.length}</h1>
</div>
);
}
this is the sample users.json
file:
[
{
"id": 1,
"name": "name"
},
{
"id": 2,
"name": "name 2"
}
]
this is the structure of the main directory:
Here is the code
Upvotes: 7
Reputation: 51
you can try to import your JSON:
import data from 'data/users.json'
Then make a length of the data
Object.keys(data).length
or use JSON.parse
Upvotes: 1