1.0.9 • Published 3 years ago

ama-use-cookis v1.0.9

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

@meksiabdou/usepagination

A custom React Hook for pagination.

npm version

Installation

$ npm i @meksiabdou/usepagination

or

$ yarn add @meksiabdou/usepagination

Usage

Here is a basic setup.

import usePagination from '@meksiabdou/usepagination';

Parameters

NameTypeDefault Value
urlStringnone
queryObject{}
countNumber10
pageNumber1
onPageChangeFunctionnull
headersObject{}

Return

NameTypedescription
dataObjectThe data is retrieved from api
pageNumberPage number
setPageFunctionSet page number
paginateFunctionFunction form pagination
loadingBooleanLoading
moreLoadingBooleanLoading on call paginate
pageCountNumbernumber of pages

Example

import React, { useState } from 'react';
import usePagination from '@meksiabdou/usepagination';


const Stores = () => {

    const url = "http://example.com/api/stores";
    const query = {active : 1};
    const count = 10;
    const currentPage = 1;
    const onPageChange = (p) => {

      window.history.pushState(
        {},
        null,
        `${window.location.origin}/#${pathname}?p=${p}`
      );
    
    };
    headers = {token : "mytoken"};

    const {
    page,
    setPage,
    data,
    loading,
    more,
    pageCount,
    paginate,
    } = usePagination({
        url : url, 
        query : query, 
        responseKeys: responseKeys,
        count: count, 
        page : currentPage,  
        onPageChange: onPageChange,
        headers : headers,
    });

    return (<div>
        {
            data.map((item, index) => {
                return <p key={index}>{item.name}</p>
            })
        }
        <button onclick={paginate}>more - page {page} / {pageCount}</button>
    </div>);
}

export default Stores;

Request

http://example.com/api/stores?limit=10&offset&active=1

Response

Output with status 200 OK:

{
    "results" : {
        "count_all" : 150,
        "data" : [
            {
                "id" : 1,
                "name" : "aliexpress",
            },
            {
                "id" : 2,
                "name" : "bengood",
            },
            {
                "id" : 3,
                "name" : "Gearbest",
            },
            ...
        ],
    },
    "status" : true,
}

Live demo

You can view/edit the sample code above on CodeSandbox.

Edit demo app on CodeSandbox

License

MIT Licensed