React table loads but disappears on clicking pagination links - javascript

I am new to React and trying to develop my first web application. What I am trying to achieve is pretty basic. I am trying to fetch some data from an API and display it in a table. To the table I am trying to add pagination so that all the records are not displayed on the same screen. I have added the page numbers but when I click on any of the page number links, the correct data in the table gets loaded but the table disappears immediately. I have no clue why this is happening. Here is my code below:
Basket.js
import React, { useState, useEffect } from "react";
import axios from "axios";
import Posts from "../Posts";
import Pagination from "../Pagination";
const Basket = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await axios.get("http://192.168.29.135:8000/aysle/baskets/");
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
//Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
//Change Page
const paginate = (pageNumber) => setCurrentPage(pageNumber);
//console.log(posts);
return (
<div>
<Posts posts={currentPosts} loading={loading} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
/>
</div>
);
};
export default Basket;
To display the data in tabular form am using the below code:
Posts.js:
import React from "react";
import edit from "../images/edit.png";
import del from "../images/delete.png";
import "./Basket/basket.scss";
const Posts = ({ posts, loading }) => {
if (loading) {
return <h2>Loading All Baskets....</h2>;
}
return (
<table className="basket-view">
<thead>
<tr id="Baskettr">
<th id="Basketth" colSpan="4">
Here are your Listings...
</th>
</tr>
<tr id="Baskettr">
{/* <th id="Basketth">Id</th> */}
<th id="Basketth">Basket Name</th>
<th id="Basketth">Basket Creation Date</th>
<th id="Basketth">Basket Modified Date</th>
<th id="Basketth">Action</th>
</tr>
</thead>
<tbody id="Baskettbody">
{posts ? (
posts.length > 0 ? (
posts.map((post, index) => {
return (
<tr id="Baskettr" key={index}>
{/* <td id="Baskettd">{basket.id}</td> */}
<td id="Baskettd">{post.basket_name}</td>
<td id="Baskettd">{post.basket_creation_date}</td>
<td id="Baskettd">{post.basket_modified_date}</td>
<td>
<button id="delBtn" title="Edit">
<img src={edit} id="BtnImg" alt="Edit" />
</button>
<button id="editBtn" title="Delete">
<img src={del} id="BtnImg" alt="Delete" />
</button>
</td>
</tr>
);
})
) : (
<tr id="Baskettr">
<td id="Baskettd">No Records to Show...</td>
</tr>
)
) : (
0
)}
</tbody>
</table>
);
};
export default Posts;
And finally, for pagination I am using the following code:
import React from "react";
const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
//console.log(totalPosts);
for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
<nav>
<ul className="pagination">
{pageNumbers.map((number) => (
<li key={number} className="page-item">
<a onClick={() => paginate(number)} href="!#" className="page-link">
{number}
</a>
</li>
))}
</ul>
</nav>
);
};
export default Pagination;
Please help me to rectify this issue. Thanks a lot for your time in advance. Here is the CodeSandBoxLink

It's all because of the href attribute "!#" in the tag. Because of it, there is a transition to a new page and all data fetched again.
You can use <button/> instead of <a/> and style it with css. example

Related

Delete Table Row not working properly with search bar

i'm new to reactjs and i'm trying to make a table that shows the information from a array of objects and have a button of delete and an input to search among the users. The delete button is working correctly when i'm not searching anything, but when i'm searching it doesn't delete the corretly row, and deletes only the first one. I see that it is because the arrays that show the table are different with and without the search being used but I don't know how to make it work.
this is the component of the table:
import { formatDate } from "../../utils/formatDate";
import "./table.css";
import { useState } from "react";
function Table(props) {
const { headerData, bodyData, type, removeItem} = props;
const isUser = type === "user";
const buildTableItems = () => {
return bodyData.map((item, index) => (
<tr className="data-tr">
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.occupation}</td>
<td>{formatDate(item.birthday)}</td>
<td>
<button className="delete-button" onClick={() => removeItem(index)}>
Delete
</button>
</td>
</tr>
));
};
return (
<div className="user-data">
<table className="user-table">
<thead>
<tr className="data-th">
{headerData.map((headerTable) => (
<th >{headerTable}</th>
))}
</tr>
</thead>
<tbody>{buildTableItems()}</tbody>
</table>
</div>
);
}
export default Table;
Here the component of the search bar:
import "./searchBar.css"
function SearchBar({ searchedData, onSearch }) {
return (
<div className="search-bar">
<label>Search</label>
<input type="text" placeholder="Search User" value={searchedData} onChange={e => onSearch(e.target.value)} />
</div>
);
}
export default SearchBar;
and here is the home:
import "./Home.css";
import React, { useEffect, useState } from "react";
import Header from "../components/Header/Header";
import Table from "../components/Table/Table";
import AddData from "../components/AddData/AddData";
import SearchBar from "../components/SearchBar/SearchBar";
import { userArr } from "../mock/users";
const Home = () => {
const headerUser = ["Name", "Email", "Occupation", "Birthday"];
const [newUserArr, setNewUserArr] = useState(userArr);
const [searchedItem, setSearchedItem] = useState("");
const searchedArray = newUserArr.filter((item) => {
if (item.name.toLowerCase().includes(searchedItem.toLowerCase())) {
return true;
}
});
function onSearch(e) {
setSearchedItem(e);
}
const addDataToArr = (form) => {
setNewUserArr([...newUserArr, form]);
};
const deleteData = (indexUserArr) => {
let restOfDataArray = newUserArr.filter(
(element, ind) => ind !== indexUserArr
);
setNewUserArr(restOfDataArray);
};
return (
<>
<Header />
<SearchBar searchedData={searchedItem} onSearch={onSearch} />
<Table
type="user"
headerData={headerUser}
bodyData={newUserArr}
removeItem={(index) => deleteData(index)}
/>
<AddData saveData={(val) => addDataToArr(val)} />
</>
);
};
export default Home;
thank you
If you have ID in your user data then use that instead of index or create id keywords using concatenate with your values here is examples.
import { formatDate } from "../../utils/formatDate";
import "./table.css";
import { useState } from "react";
function Table(props) {
const { headerData, bodyData, type, removeItem} = props;
const isUser = type === "user";
const buildTableItems = () => {
return bodyData.map((item, index) => (
<tr className="data-tr">
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.occupation}</td>
<td>{formatDate(item.birthday)}</td>
<td>
<button className="delete-button" onClick={() => removeItem(`${item.name}${item.email}${item.occupation}`)}>
Delete
</button>
</td>
</tr>
));
};
return (
<div className="user-data">
<table className="user-table">
<thead>
<tr className="data-th">
{headerData.map((headerTable) => (
<th >{headerTable}</th>
))}
</tr>
</thead>
<tbody>{buildTableItems()}</tbody>
</table>
</div>
);
}
export default Table;
And here is your delete method ${item.name}${item.email}${index}
const deleteData = (data) => {
let restOfDataArray = newUserArr.filter(
(element, ind) => `${element.name}${element.email}${element.occupation}` !== data
);
setNewUserArr(restOfDataArray);
};
This will fixed your problem. If this doesn't work then you need to use ID to resolve this problem. There is a possibility that ${item.name}${item.email}${item.occupation} can be duplicates.
Never use index ever for deleting or any other operations. Use always ID.

how to pass Project ID to another component in react.js

**Hello Guys, i create a table in MyProjectList.js file for displaying project data now i want, If user Click on table row then i want to pass this clicked Project Id to Collection.js file to use in query to compare.
*this is MyProjectList.js file.
import React from "react";
import { useEffect, useState } from "react";
import { Table } from "react-bootstrap";
import axios from "axios";
import _ from "lodash";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
const pageSize = 10;
export default function MyProjectsList() {
let navigate = useNavigate();
const [projects, setProjects] = useState();
const [paginatedProject, setPaginatedProject] = useState();
const [currentPage, setCurrentPage] = useState(1);
const userState = useSelector(state=> state.loginUserReducer)
const {currentUser} =userState;
const coordinatorId = currentUser.id;
useEffect(() => {
axios.post("http://localhost:4000/coordinatorsProjects",
{
coordinatorId : coordinatorId
}).then((res) => {
console.log(res.data,'==>>> this is coordinator projects');
setProjects(res.data);
setPaginatedProject(_(res.data).slice(0).take(pageSize).value());
});
}, [coordinatorId]);
const pageCount = projects ? Math.ceil(projects.length / pageSize) : 0;
const pages = _.range(1, pageCount + 1);
const pagination = (pageNo) => {
setCurrentPage(pageNo);
const startIndex = (pageNo - 1) * pageSize;
const paginatedProject = _(projects)
.slice(startIndex)
.take(pageSize)
.value();
setPaginatedProject(paginatedProject);
};
//***using this function i am nevigate user to colletion.js component. how to pass project id this?
const onRowClick = async (e) => {
navigate("/coordinators/collection")
console.log(e)
}
return (
<>
<div className="container">
{/* {loading && (<Loading/>)} */}
{/* {error && alert("Error occured to get data")} */}
{!paginatedProject ? (
"ERROR: Data Not Found. Please check your internet connection!"
) : (
<Table className="table table-hover table-light table-bordered shadow">
<thead className="thead-dark">
<tr>
<th scope="col">Project Name</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Budget Rs.</th>
<th scope="col">Remaining Rs.</th>
</tr>
</thead>
<tbody>
{paginatedProject.map((user, _id) => (
<tr onClick={ onRowClick } key={_id}>
<td>{user.projectName}</td>
<td>{user.startDate}</td>
<td>{user.endDate}</td>
<td>{user.budget}</td>
<td>{user.remaining}</td>
</tr>
))}
</tbody>
</Table>
)}
<nav className="d-flex pagination justify-content-center ">
<ul className="pagination ">
{pages.map((page) => (
<li
className={
page === currentPage ? "page-item active" : "page-item"
}
>
<p className="page-link" onClick={() => pagination(page)}>
{page}
</p>
</li>
))}
</ul>
</nav>
</div>
</>
);
}
*this is Collection.js file.
import React from 'react';
import { useEffect, useState } from "react";
import { Table } from "react-bootstrap";
import axios from "axios";
import _ from "lodash";
const pageSize= 10;
export default function Collection () {
const [donors, setDonors] = useState()
const [paginatedDonors, setPaginatedDonors] = useState()
const [currentPage, setCurrentPage] = useState(1)
useEffect(() => {
axios.post("http://localhost:4000/coordinatorsCollection",
{
projectID : "7"
}).then((res)=>{
console.log(res.data);
setDonors(res.data);
setPaginatedDonors(_(res.data).slice(0).take(pageSize).value());
});
}, []);
const pageCount= donors? Math.ceil(donors.length/pageSize) :0;
const pages = _.range(1, pageCount+1)
const pagination= (pageNo) =>{
setCurrentPage(pageNo)
const startIndex = (pageNo -1) * pageSize;
const paginatedDonors = _(donors).slice(startIndex).take(pageSize).value();
setPaginatedDonors(paginatedDonors)
}
return (
<>
<div className='container'>
<h3 align="center">Collection of users</h3>
{/* {loading && (<Loading/>)} */}
{/* {error && alert("Error occured to get data")} */}
{!paginatedDonors ? ("ERROR: Data Not Found. Please check your internet connection!"):(
<Table className="table table-hover table-light table-bordered shadow">
<thead className="thead-dark">
<tr>
<th scope="col">Donor Name</th>
<th scope="col">Contact No</th>
<th scope="col">Amount</th>
<th scope="col">Project</th>
<th scope="col">Project Budget</th>
<th scope="col">Donate Date.</th>
</tr>
</thead>
<tbody >
{paginatedDonors.map((donors, id) => (
<tr key={id}>
<td>{donors.name}</td>
<td>{donors.mobileNo}</td>
<td>{donors.amount}</td>
<td>{donors.project}</td>
<td>{donors.projectBudget}</td>
<td>{donors.donateDate}</td>
</tr>
))}
</tbody>
</Table>
)}
<nav className="d-flex pagination justify-content-center ">
<ul className="pagination ">
{
pages.map((page)=>(
<li className={
page === currentPage ? "page-item active" : "page-item"
}>
<p className="page-link"
onClick={()=>pagination(page)}
>{page}</p></li>
) )
}
</ul>
</nav>
</div>
</>
)
};
temporarily i am sending '7' (hard coded) to the api to check and it working fine. But i want clicked project id in this.
thank you!!!
You need only one id. You can get this id when you mapping projects in MyProjectList.js file at this line paginatedProject.map((user, _id) => ().
Just get projectid from user and then send it into onClick like this:
onCLick = {(e) => onRowClick(e, user.projectId)}
If I were you I would use react context for this situation because your issue is the meaning of using react context; React context is a general state that you can set or edit or use your general state in all your components easily

How to implement pagination to a list data in a table in react.js?

Quick help needed! I have list of data rendered in a table from an API. I need this list of data to be paginated into small list of data.
Here is the code for VendorsDetail.js which displays list of data in a table
import React, { useState, useEffect } from "react";
import HelpOutlineIcon from "#mui/icons-material/HelpOutline";
import axios from "axios";
import VendorDetailsBrief from "./VendorDetailsBrief";
import Pagination from "./Pagination";
const VendersDetail = ({ textMe }) => {
const [data, setData] = useState({});
const foo = "cpe:2.3:a:oracle:peoplesoft_enterprise:8.22.14";
const baseURL =
"https://services.nvd.nist.gov/rest/json/cves/1.0?cpeMatchString=" + foo;
useEffect(() => {
axios
.get(baseURL)
.then((response) => {
setData(response.data);
})
.then(
(response) => {},
(err) => {
alert(err);
}
);
}, []);
const DisplayData = data?.result?.CVE_Items?.map((vender) => {
return (
<tr>
<td className="color_id font-semibold">
{vender?.cve?.CVE_data_meta?.ID}
</td>
<td className="w-96">
{vender?.cve?.description?.description_data?.[0]?.value}
</td>
<td>{vender?.impact?.baseMetricV2?.exploitabilityScore}</td>
<td>{vender?.impact?.baseMetricV2?.severity}</td>
<td>{vender?.impact?.baseMetricV2?.impactScore}</td>
</tr>
);
});
return (
<div className="z-100 flex justify-center items-center mt-10">
<div className="text-black">
<div className="rounded overflow-hidden flex justify-center items-center">
<table class="table table-striped ">
<thead>
<tr>
<th>Vuln ID</th>
<th>Description Data</th>
<th>Exploitability Score</th>
<th>Severity</th>
<th>Impact Score</th>
</tr>
</thead>
<tbody>{DisplayData}</tbody>
</table>
</div>
</div>
</div>
);
};
export default VendersDetail;
Pagination.js
import React from "react";
const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
<nav>
<ul className="pagination">
{pageNumbers.map((number) => (
<li key={number} className="page-item">
<a onClick={() => paginate(number)} href="!#" className="page-link">
{number}
</a>
</li>
))}
</ul>
</nav>
);
};
export default Pagination;
How can I implement pagination in this particular data list? Thanks
Create Parent Component with logic to get data from URL and pagination onCLick handler.
Parent Component should render VendorsDetail component and Pagination component.
Pass data to be displayed to VendorsDetails component and getSubsequentData handler to Pagination component.
If user click on specific page number, call getSubsequentData handler with specific argument, that updates the state of the parent component, which will updates VendorsDetail component.
const ParentComponent = () => {
const [data, setData] = useState({})
useEffect = (() => {
// axios call to get initial data from the URL
})
getSubsequentData = (URL) => {
// axios call to get data based on the URL.
// LInk this to pagination onClick
}
return(
<VendorsDetail data={data} />
<Pagination getNextData={getSubsequentData}/>
)
}

tried a lot but not able to make deletehandler function working. here is my code

This is my librarylist component in which i pass deletehandler function to delete the row from library management. I don't know which part of the code is causing the problem. Any helps/suggestions are welcome.
LibraryBookList.js
const LibraryBookList = (props) => {
const[database, setDatabase]=useState()
const deleteHandler = (bookdataId) => {
const newDatabase=[...database];
const index= database.findIndex((bookdata)=>bookdata.id===bookdataId)
newDatabase.splice(index,1)
setDatabase(newDatabase);
} ;
return (
<ul className={classes.list}>
{props.database.map((bookdata) =>
(<LibraryBook
key={bookdata.key}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
))}
</ul>
)};
here i pass deletehandler via props
LibraryBook.js
const LibraryBook = (props) => {
return (
<li>
<table className={classes.table}>
<tbody>
<tr className={classes.table_row}>
<td className={classes.row_data}>{props.serialno}</td>
<td className={classes.row_data}>{props.pages}</td>
<td className={classes.row_data}>{props.bookname}</td>
<td className={classes.row_data}>{props.author}</td>
<td className={classes.row_data}>{props.publisher}</td>
<td>
<button className={classes.delete_btn} onClick={(props.onSelect(props.id))}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
export default LibraryBookList;
**BookData.js **
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
console.log("data", data);
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table className={classes.table}>
<thead>
<tr className={classes.table_row}>
<th className={classes.row_heading}>Serial No</th>
<th className={classes.row_heading}>Pages</th>
<th className={classes.row_heading}>Book Name</th>
<th className={classes.row_heading}>Author</th>
<th className={classes.row_heading}>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;
NewDataBase.js
const NewDataBase = () => {
const history=useHistory();
const addDataHandler = (bookData) => {
console.log('bookData',bookData);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json",
{
method: "POST",
body: JSON.stringify(bookData),
headers: {
"Content-type": "application/json",
},
}
).then(()=>{
history.replace('/')
})
};
return (
<section>
<DataBaseForm onAddNewData={addDataHandler} />
</section>
);
};
export default NewDataBase;
The code has a few issues: 1) props.onSelect(props.id) inside onClick. Instead you should give a referance to that function. 2) You didn't have anything in database state before you click delete button. That is why ... spread operator didn't work 3) You are displaying props.database instead of database state. That is way the changes didn't show up even after you deleted a bookdata. I also fixed some small issues. Now it is working perfectly:
// !! you can put all the code into one file and run for testing.
// !! I removed stylings as I didn't have the source
import {useState, useEffect} from 'react'
const LibraryBooklist = (props) => {
const[database, setDatabase]=useState(props.database)
const deleteHandler = (bookdataId) => {
const newDatabase=database.filter((bookdata)=>bookdata.id!==bookdataId);
setDatabase(newDatabase);
}
return (
<ul>
{database.map((bookdata) =>
<LibraryBook
key={bookdata.id}
id={bookdata.id}
bookname={bookdata.bookName}
author={bookdata.author}
publisher={bookdata.publisher}
pages={bookdata.pages}
serialno={bookdata.serialNo}
onSelect={deleteHandler}
/>
)}
</ul>
)};
const LibraryBook = (props) => {
const {id, onSelect} = props
return (
<li>
<table>
<tbody>
<tr>
<td>{props.serialno}</td>
<td>{props.pages}</td>
<td>{props.bookname}</td>
<td>{props.author}</td>
<td>{props.publisher}</td>
<td>
<button onClick={() => onSelect(id)}>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</li>
)}
const BookData = (props) => {
const [isLoading, setIsLoading] = useState(true);
const [loadedLibrarydata, setLoadedLibrarydata] = useState();
useEffect(() => {
setIsLoading(true);
fetch(
"https://librarymanagement-70ab2-default-rtdb.firebaseio.com/database.json"
)
.then((response) => {
// console.log('response',response.json())
return response.json();
})
.then((data) => {
const database = [];
for (const key in data) {
const bookdata = {
id: key,
...data[key],
};
database.push(bookdata);
}
setIsLoading(false);
setLoadedLibrarydata(database);
});
}, []);
if (isLoading) {
return (
<section>
<p>Loading.....</p>
</section>
);
}
return (
<section>
<h1>Book Data Base</h1>
<table>
<thead>
<tr>
<th>Serial No</th>
<th>Pages</th>
<th>Book Name</th>
<th>Author</th>
<th>Publisher</th>
</tr>
</thead>
</table>
{loadedLibrarydata && loadedLibrarydata.length && (
<LibraryBooklist database={loadedLibrarydata} />
)}
</section>
);
};
export default BookData;

How to print/render in a table Firebase information REACT JS

Before posting I always google, youtube, forums or try to figure it by myself or even check other people questions that are similar but I'm stuck sadly.
So I'm using firestore database, the user can create a "student" and the data is the firestore is saved like this:
It saves the course, Name, school, and the UID of the person that create it. So far I have no problems importing that information to the firestore now the issue is to bring it back in a table, I do not understand why is not being printed.
The console Log is printing all the students 1 by 1 + all the students in the array (is cause is going through all the info)
Now as you can see the table is empty! and I do not understand WHY!!! Very frustrated
This are snips of the code that are relevant:
DB part:
useEffect(() => {
db.collection('usuarios').doc(user.uid).collection('estudiantes')
.get().then((snapshot) => {
(snapshot.forEach(doc => {
const data = doc.data();
estudiantes.push(data)
console.log(doc.data());
console.log(estudiantes)
}))
})
}, []);
Map/Rendering
<tbody>
{estudiantes.map((e) => (
<tr >
<td>
<input onChange = {(event) => {
let checked = event.target.checked;
}}
type="checkbox" checked = "">
</input>
</td>
<td >{e.name}</td>
<td >{e.school}</td>
<td >{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
Whole Code:
import React, { useState, useEffect } from 'react'
import { auth, db } from './firebase';
import "./ListadoEstudiantes.css"
import data from "./mock-data.json"
import { useHistory } from 'react-router-dom';
import { Checkbox } from '#material-ui/core';
function ListadoEstudiantes({user}) {
const [contacts, setContacts] = useState(data);
const history = useHistory("");
const crearEstudiante = () => {
history.push("/Crear_Estudiante");
}
const realizarPedidos = () => {
history.push("/Crear_Pedidos");
}
const estudiantes = [];
useEffect(() => {
db.collection('usuarios').doc(user.uid).collection('estudiantes')
.get().then((snapshot) => {
(snapshot.forEach(doc => {
const data = doc.data();
estudiantes.push(data)
console.log(doc.data());
console.log(estudiantes)
}))
})
}, []);
return (
<div className="listadoEstudiantes">
<div className="estudiantes_container">
<h1 className = "estudiantes_container_h1">Listado de estudiantes</h1>
<button onClick={crearEstudiante} className = "crear_estudiante_boton">Crear Estudiantes</button>
<h3 className = "estudiantes_container_h3">*Para realizar su pedido seleccione a los estudiantes</h3>
<div className ="tableContainer">
<table>
<thead>
<tr className="Lista">
<th>
<input type="checkbox"></input>
</th>
<th>Nombre</th>
<th>Colegio</th>
<th>Grado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
{estudiantes.map((e) => (
<tr >
<td>
<input onChange = {(event) => {
let checked = event.target.checked;
}}
type="checkbox" checked = "">
</input>
</td>
<td >{e.name}</td>
<td >{e.school}</td>
<td >{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
</table>
</div>
<div className="space" />
<button onClick={realizarPedidos} className = "crear_estudiante_boton">Realizar Pedidos</button>
<div className="space" />
</div>
</div>
)
}
export default ListadoEstudiantes
I think that's it, the user is from the Firestore database also the data that I'm importing is a fake data that I used to test the table (and renders with no issues) that can be ignored.
This is how it looks on the fake data and how it should look with the real data (THAT DOESN'T WORK! :'3)
estudiantes should be a local state of the component. Therefore, it needs to be captured as a state and use it for table data rendering as follows.
setEstudiantes is a setState function which updates the state asynchornously. Therefore, in order to check the updated state, you need to have the console.log("estudiantes: ", estudiantes) inside the render method (not after setEstudiantes(tempData)). Otherwise, you won't be able to see the updated state.
import React, { useState, useEffect } from "react";
import { auth, db } from "./firebase";
import "./ListadoEstudiantes.css";
import data from "./mock-data.json";
import { useHistory } from "react-router-dom";
import { Checkbox } from "#material-ui/core";
function ListadoEstudiantes({ user }) {
const [contacts, setContacts] = useState(data);
const [estudiantes, setEstudiantes] = useState([]);
const history = useHistory("");
const crearEstudiante = () => {
history.push("/Crear_Estudiante");
};
const realizarPedidos = () => {
history.push("/Crear_Pedidos");
};
useEffect(() => {
db.collection("usuarios")
.doc(user.uid)
.collection("estudiantes")
.get()
.then((snapshot) => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
console.log(doc.data());
console.log("Temp Data: ", tempData);
});
setEstudiantes(tempData);
});
}, []);
console.log("estudiantes: ", estudiantes);
return (
<div className="listadoEstudiantes">
<div className="estudiantes_container">
<h1 className="estudiantes_container_h1">Listado de estudiantes</h1>
<button onClick={crearEstudiante} className="crear_estudiante_boton">
Crear Estudiantes
</button>
<h3 className="estudiantes_container_h3">
*Para realizar su pedido seleccione a los estudiantes
</h3>
<div className="tableContainer">
<table>
<thead>
<tr className="Lista">
<th>
<input type="checkbox"></input>
</th>
<th>Nombre</th>
<th>Colegio</th>
<th>Grado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
{estudiantes.map((e) => (
<tr>
<td>
<input
onChange={(event) => {
let checked = event.target.checked;
}}
type="checkbox"
checked=""
></input>
</td>
<td>{e.name}</td>
<td>{e.school}</td>
<td>{e.grade}</td>
<td></td>
</tr>
))}
</tbody>
</table>
</div>
<div className="space" />
<button onClick={realizarPedidos} className="crear_estudiante_boton">
Realizar Pedidos
</button>
<div className="space" />
</div>
</div>
);
}
export default ListadoEstudiantes;

Categories

Resources