Closed darkterminal closed 1 year ago
If you would like to continue contributing to open source and would like to do it with an awesome inclusive community, you should join our GitHub Organisation - we help and encourage each other to contribute to open source little and often :neckbeard:. Any questions let us know.
Wow, impressive work :eyes: !!!
Thank you... but it's worth for me (a forgetful)
I will work on the SCP website to list them!
We need to clarify the collection directories.
Let's open a discussion about it ==> https://github.com/StreetCommunityProgrammer/metaphore/discussions/11
This issue will generate as story in our Street Community Programmer site. Thanks for your story!
Do you have CSS for this?
This issues is closed, if you have any question please move in this detail story comment section.
Metaphore Name
React Table - Sever Side Pagination, Search, Sort/Order
Share your metaphore story!
TLDR
This is a complete guide how I manage datatable in React JS project using
react-table
andprisma
ORM. Let's start!Client Side
Dependencies
The component above generates a table with global filtering, pagination, sorting, and loading features. It uses the following dependencies:
@heroicons/react
for icons,react
for the base library, andreact-table
for generating the table.Table Instance
TablePagination
is a function that receives props that are used to display the table. The props arecolumns
for the table columns,data
for the data to be displayed,fetchData
for fetching data when pagination is changed,loading
to display the loading icon,pageCount
for the number of pages,totalRow
for the total row count, andactions
for extra action buttons on the filter row.The function creates a table instance using
useTable
fromreact-table
and initializes the state of the table to the first page and ten rows per page. It also setsmanualPagination
,manualGlobalFilter
, andmanualSortBy
totrue
so that the component has control over those features.Global Filtering
The
GlobalFilter
component displays the input search box used for filtering the table data. It also receives the pre-filtered row count and usesuseAsyncDebounce
to delay the search filter until the user stops typing. This helps reduce unnecessary calls to the server when searching.Table Body
The table body and header are then created using the
getTableProps
andgetTableBodyProps
methods from the react-table library. TheheaderGroups
and page are used to map over the header columns and table data, respectively, using the map function. TheprepareRow
method is called on each row to enable the use of thegetRowProps
andgetCellProps
methods to style the row and cell.Sorting
The sorting feature is enabled by adding the
getHeaderProps
method to the column header and using thecolumn.getSortByToggleProps()
method. This method updates thesortBy
object in the table state and adds the appropriate class and icon to the sorted column.Pagination
The pagination feature is enabled using
usePagination
and thepageCount
,canPreviousPage
,canNextPage
,pageOptions
,gotoPage
,nextPage
,previousPage
, andsetPageSize
methods. These methods are used to generate the pagination controls and update the table state when the user interacts with them.Loading
Finally, the loading feature is enabled by checking if
loading
is true and displaying a loading icon in the table while data is being fetched from the server.Helpers
When we use API for pagination we also need a helper to serialized endpoint url before sending to server.
This code defines an object named
Util
, which contains several utility functions:isArray
checks whether a given value is an array or not. It does this by using theObject.prototype.toString.call
method, which returns a string representing the object's type. If the string matches the expected value "[object Array]
", then the value is considered an array.isNil
checks whether a given value is null or undefined. It does this by using thetypeOf
method to check if the type of the value is "undefined".typeOf
checks whether the given value is of a certain type. It does this by comparing the type of the value to the type provided as an argument. If the types match, it returns true.funEach
is a utility function that can iterate over an array or an object and execute a given function for each element. If the given value is null or undefined, the function simply returns. If the value is not an object, it converts it to an array. If the value is an array, it iterates over each element and calls the given function with the element, index, and array as arguments. If the value is an object, it iterates over each key-value pair and calls the given function with the value, key, and object as arguments.The code then exports a function named
uriSerialized
. This function takes an objectparams
as input and returns a string representing the object as a URI-encoded string.The function uses
Util.funEach
to iterate over the object and create an array of key-value pairs, where each value is URI-encoded. If the value is an array, the key is modified by appending "[]" to the end. The key-value pairs are then concatenated into a string with "&" as the separator, and returned.Services
For example when we need to create datatable for roles designation on a system.
This function makes a GET request to an API endpoint for a role datatable using the Axios HTTP client library.
The function accepts an optional parameter
queryOptions
which can be used to pass in query parameters to the API endpoint. IfqueryOptions
is not null, it will be converted to a serialized URI string using theuriSerialized
function imported from "../Utils/uriSerialized". The serialized URI string is then appended to the API endpoint URL.The function then sends the HTTP request to the API endpoint using axios, and awaits for the response data. If the request is successful, the response data is returned. If the request fails, the error message is logged to the console and the function returns
false
.The Role Datatable
Woooooooooooooooooooooooooo.... implementing in
RoleDatatable
componentThis is a functional React component that fetches data from the server, displays it in a paginated table, and provides the user with some action buttons for each item.
The component uses the
useState
hook to maintain its internal state, which includesdata
,loading
,pageCount
, andtotalRow
. ThefetchData
function is auseCallback
hook, which makes an API call to the server with some query parameters to fetch the data, updates the state variables, and sets the loading flag.The component also uses the
useMemo
hook to memoize thecolumns
object that contains an array of objects, which define the headers of the table columns, their accessor functions, and aCell
function that returns the corresponding value for each row. The last column of the table has two buttons,PencilSquareIcon
andTrashIcon
, to allow the user to edit or delete an item.The
TablePagination
component is a custom component that receivescolumns
,data
,fetchData
,loading
,pageCount
, andtotalRow
as its props. This component is responsible for rendering the table, paginating it, and displaying theloading
spinner while the data is being fetched. When the user clicks on the pagination links,fetchData
is called with the new page index and page size, which triggers a new API call to the server with the updated query parameters.Finally, the component is exported as the default export, which can be imported and used in other parts of the application.
That's the client side things!!! Terrace done!
Server Side
Now move on the server side, we will use
prisma
as ORM in Express API.Dependencies:
Role Datatable Model
function called
roleDatatable
that queries a database to retrieve a paginated list of roles based on the given search criteria, sorting and pagination.The function takes four optional parameters:
page
,limit
,search
andorder
.page
andlimit
are used to determine the page size and the number of records to return, while search is used to filter the records based on a text string. order is an array that specifies theorder
in which the records should be sorted.Inside the function, the
paginate
andoffset
variables are used to calculate the number of records to skip and take. Thesort
,orderKey
, andorderDirection
variables are used to specify the order by which the records should be sorted.The function then queries the database using
db.roles.findMany()
, passing in the search criteria, pagination and sorting options. It also queries the total count of roles that match the search criteria, which is used to calculate the total number of pages.The function returns an object that contains the paginated roles, the total number of rows, and the total number of pages. If an error occurs, it logs the error and returns false.
Helpers
I need to format server response that sent to client using
formatResponse
helperThe function takes in four parameters:
type
(a string),message
(a string with a default value of "No description"),data
(an array with a default value of an empty array), andpagination
(an optional object).The function returns an object with the properties
type
,message
, anddata
, and, ifpagination
is notnull
, includes thepagination
object as well.Before returning the object, the function checks if the
type
parameter is one of the allowed types by comparing it to an array of allowed types. If thetype
is not allowed, an error is thrown indicating which types are allowed.Router
Let's create API route for Role Datatable
his code sets up a router for an endpoint that returns a datatable of roles. The endpoint listens for GET requests to the '/datatable' path. When a request is received, it extracts the query parameters (page, limit, search, and order) from the request. It then calls the
roleDatatable
function from the Roles model with the query parameters. IfroleDatatable
returns data, the endpoint sends a response with a 200 status code and a JSON object containing the datatable data and pagination information. IfroleDatatable
returns no data, the endpoint sends a response with a 404 status code and a JSON object containing an error message.The
formatResponse
function is used to format the response into a standard structure. It takes four parameters: type (a string that indicates the type of response), message (a string that provides additional details about the response), data (the data to be included in the response), and pagination (an optional object that contains pagination information). It returns an object that includes the four parameters.Fiuh!!!! that's it... no puncline...
A demo/repos link
No response