0.0.5 • Published 2 days ago

ezhooks v0.0.5

Weekly downloads
1
License
ISC
Repository
github
Last release
2 days ago

ezhooks

This is a custom hook for data processing from the frontend

Installation

npm install ezhooks

or

yarn add ezhooks

useMutation

Hook form data mutation

Generic Props

NameTypeDescription
defaultValue*TDefault values for the form.
scenarioObjectDivide data in the form of scenarios
formatObjectFuncProvides the format value when input

Usage

import useMutation from 'ezhooks/lib/useMutation';

const App = () => {
    const form = useMutation({
        defaultValue: {
            title: '',
            contact: {
                phone: '',
                office: ''
            },
            item: [],
            rating: 0
        }
    })
    ...
}

Props

processing

NameTypeDescription
processingboolGives an indication of the process in progress.
form.processing ? "loading...." : <div>...</div>;

data

NameTypeDescription
dataTShow all data.
console.log("Data", data);

setData(value*)

NameTypeDescription
setDatafuncShow all data.
...
return <div>
    <input type='text' name='title' onChange={e => form.setData({[e.target.name]: e.target.value})} />
</div>

Nested Value

for nested values we break them down using dots

set value if object nested (object)

...
return <div>
    <input type='text' onChange={e => form.setData({'contact.phone': e.target.value})} />
    <input type='text' onChange={e => form.setData({'contact.office': e.target.value})} />
</div>

set value value if array object

...
return <div>
    <input type='text' onChange={e => form.setData({'item.0.label': e.target.value})} />
    <input type='text' onChange={e => form.setData({'item.0.item.1.label': e.target.value})} />
</div>

value(key*, defaultValue = '')

NameTypeDescription
valuefuncGet value by key.
...
return <div>
    <input ... value={form.value('title')}/>
    <input ... value={form.value('contact.phone')}/>
    <input ... value={form.value('item.0.label')}/>
</div>

Nested Get Value

for get values we break them down using dots

increment(value*)

NameTypeDescription
incrementfuncincrease value.
...
return <div>
   <input type='text' onChange={e => form.increment({'rating': 1})} />
</div

Nested Increment

for nested values we break them down using dots

decrement(value*)

NameTypeDescription
decrementfuncdecrease value.
...
return <div>
   <input type='text' onChange={e => form.decrease({'rating': 1})} />
</div

Nested Decrement

for nested values we break them down using dots

addItem(key*, value*, position)

NameTypeDescription
addItemfuncadd array value.
positionstring, numberstart, endornumber
...
form.addItem('item', {label: ''}) //default position:end
form.addItem('item', {label: ''}, 1) //position by number:index start by 0

Nested Decrement

for nested values we break them down using dots

removeItem(key*, condition)

NameTypeDescription
removeItemfuncadd array value.
conditionnnumber,funcnumber of index data or func(condition)
...
form.removeItem('item', 0)
form.removeItem('item', (item) => item.label === 'test') //condition with function

Nested Decrement

for nested values we break them down using dots

reset()

NameTypeDescription
resetfuncclear value.
...
form.reset()

send(props*)

NameTypeDescription
service*funcservice.
scenariostringchoose a scenario for the data.
exceptarrayoutputs the data that will be sent based on the key.
onlyarraySelect the data to be sent based on the key.
includearray, objectAdd data to be sent.
onSuccessfuncThe function callback on success and returns a response.
onErrorfuncThe function calls back on failure and returns a error.
onAlwaysfuncfunction calls back same 'finally' on promise
...

function onSubmit(){
    form.send({
        service: (event) => fetch('http:example.com', {
            method: 'post',
            body: JSON.stringify(event.data),
            signal: event.ctr.signal
        }),
        onSuccess: (resp) => {

        },
        onError: (err) => {},
        onAlways: () => {}
    })
}

// import { EventSend } from 'ezhooks/lib/useMutation' if typescripts
const addExample = async(event : EventSend) => {
return fetch('http:example.com', {
            method: 'post',
            body: JSON.stringify(event.data),
            signal: event.ctr.signal
}).then(resp => resp.json())
}

function onSubmit(){
    form.send({
        service: addExample,
        onSuccess: (resp) => {},
        onError: (err) => {},
        onAlways: () => {}
    })
}

the service can use another method request: GET, PUT, POST, DELETE or PATH

with scenario

const form = useMutation({
    ...
    scenario: {
        create: ['title'],
        update: ['id', 'title']
    }
}
...
function onSubmit(){
    form.send({
        ...
       scenario: 'create'
    })
}

with except

...
function onSubmit(){
    form.send({
        ...
       except: ['title']
    })
}

with only

...
function onSubmit(){
    form.send({
        ...
       only: ['rating']
    })
}

with include

...
function onSubmit(){
    form.send({
        ...
       include: [...value] // or {...value}
    })
}

useFetch

Hook for get data

Generic Props

NameTypeDescription
service*funcdefault values for the form.
selectorfuncdivide data in the form of scenarios
defaultValueTdefault values for the data
disabledOnDidMountbooldisable call request for first time render
debounceTimenumberdelay time request in milliseconds
depsarraydependcies
getDatafuncfunction callback for get data

Usage

import useFetch from 'ezhooks/lib/useFetch';

const App = () => {
    const fetch = useFetch({
        service: () => fetch('http://example.com').then(resp => resp.json())
        selector: (resp) => resp.products,
        defaultValue: [] //or {}
    })
    ...
}

for service can use another service request like fetch, axios ..etc

Props

loading

NameTypeDescription
loadingboolGives an indication of the process in progress.
form.loading ? "loading...." : <div>...</div>;

isEmpty

NameTypeDescription
isEmptyboolGives an indication of if empty data.
form.isEmpty ? "Data not available" : <div>...</div>;

data

NameTypeDescription
dataTvalue.
form.data;

query

NameTypeDescription
queryobjectquery parameters
form.query;

setQuery(value*)

NameTypeDescription
setQueryfuncfunction for set query
<input
  type="search"
  name="keywords"
  onChange={(e) => fetch.setQuery({ [e.target.name]: fetch.target.value })}
/>

getQuery(key*, defaultValue = '')

NameTypeDescription
setQueryfuncfunction for set query
<input type='search' name='keywords' ... value={fecth.getQuery('keywords')}) />

refresh()

NameTypeDescription
refreshfuncrecall request
<button onClick={fetch.refresh}>Reload</button>

clear(fields?: {except, only})

NameTypeDescription
clearfuncfunction for clear all query or some query by key
<button onClick={ ()=> fetch.clear()}>Reset All</button>
<button onClick={ ()=> fetch.clear({only: ['keywords']})}>Reset only keywords</button>
<button onClick={ ()=> fetch.clear({except: ['keywords']})}>Reset excpet keywords</button>

has(key*)

NameTypeDescription
hasfuncfunction for check query key is exists
if (fetch.has("keywords")) {
  console.log("exists");
}

cancel()

NameTypeDescription
cancelfunccancel request pending
<button onClick={fetch.cancel}>Cancel</button>

useTable

Hook for get request with pagination

Generic Props

PropsTypeDescription
service*funcservice
selector*funcfunction for select data from response API
total*funcfunction for select total from response API
disabledOnDidMountbooldisable for first time render
replaceUrlboolinclude replace url
sortobjset object for sort in url
paginationobjpagination for data

Props

PropsTypeDescription
loadingboolloading indication
totalnumbertotal
dataTdata
orderBystringdisplays sorting by column
orderasc,descdisplays sort by
query(?key, ?defaultValue)funcget all parameters or based on key
setTotal(value*)funcgive the total value manually
setQuery(value*)funcset parameter
onSort(key*)funcfunction to sort by key
clear(?{except, only})funcfunction to clear parameters
remove(?key, ?resetPage)funcremove key parameter and reset page to number
reload()funcreload
isEmptyboolget an empty data indication
has(key*)boolfunction to check key parameters
paginationobj...

Pagination Props

PropsTypeDescription
pagenumbernumber of page
fromnumber...
tonumber...
lastPagenumberget the page number of the last available page.
perPageOptionsnumber[]get the page size options
perPagenumberthe number of items to be shown per page
setPage(value*)funcset page manual
setPerPage(value*)funcset size page manual
nextButton()func...
backButton()func...
firstButton()func...
lastButton()func...
onPerPageChangefuncfunction for size per page
textstringsummary
import {useTable} from 'frhooks'
const App = () => {
  const table = useTable({
   ...
    // this option for custom sort
    sort: {
      params: {
        order: "order",
        orderBy: "orderBy",
      },
      order: "desc", // Note: default order, default: desc
      orderBy: "id", // Note: default orderBy, default: id
    },
    // this option for custom pagination
    pagination: {
      params: {
        page: "page",
        perPage: "perPage",
      },
      startPage: 1,// default page, default: 1 or 0
      perPage: 10,// default perPage, default: 10,
      perPageOptions: [5, 10, 15, 25],
      from: (total, page, size, df) => page - 1 + (df === 0 ? 1 : 0)) * size +
      (total === 0 ? 0 : df === 0 ? 1 : df),
      to: (total, page, size, df) =>  Math.min(total, (page + (df === 0 ? 1 : 0)) * size),
      lastPage: (total, size) => Math.max(0, Math.ceil(total / size)), // formula
      disableFirst: (total, page, df) => total !== 0 && page === df,
      disableLast: (total, page, lp) => total !== 0 && page === lp,
    },
  })

  render <div>
      <div>
      <input type="text" value={table.query('title', '')} onChange={e => table.setQuery({title: e.target.value})} />
          {table.pagination.text} //summary

          <button {...table.pagination.firstButton()}>prev</button>
          <button {...table.pagination.backButton()}>prev</button>
          {table.pagination.page}
          <button {...table.pagination.nextButton()}>next</button>
          <button {...table.pagination.lastButton()}>next</button>

        <button onClick={() => table.onOrder("name")}>
            {table.order}-{table.orderBy}
        </button>

        <button onClick={table.clear}>Clear</button>
        <button onClick={table.reload}>Reload</button>
     </div>

      <table>
        <thead>
          <tr>
            <td>No</td>
            <td>Title</td>
          </tr>
        </thead>

        <tbody>
          {table.loading ? 'loading...' : null}

          {table.data.map((v: any, i) => (
            <tr key={i}>
              <td>{table.data.from + (i+1)}</td>
              <td>{v.title}</td>
            </tr>
          ))}
        </tbody>
      </table>
  </div>
}

useFetch & useTable

additional props array data for manipulation data

PropsTypeDescription
add(value*, ?position)func, position:end,start,numberadd data,
update(index or (value) => boolean, value*)funcupdate value by index
destroy(index or (value) => boolean)funcdelete data by index

useSValidation

server validation

Generic Props

NameTypeDescription
service*funcservice.
data*objectdata
message*ObjFuncfunction for set message
param*objparam field

Usage

//API Response
error: [
    {field: "title", type: "required"},
]

or

error: {
    field: 'title',
    type: 'required
}
import useSValidation from 'ezhooks/lib/useSValidation';

const App = () => {
    const server = useSValidation({
       service: (event) => {
        fetch("http://example/validation", {method: 'post', body: event.data})
        .then((resp) => resp.json())
        .then((resp) => {
          event.parser(resp.error);
        });
    },
    data: {
        title: "",
    },
    message: {
      required: (resp) => "this field is required",
    },
    param: {
        path: "field",
        type: "type"
    }
    })
    ...
}

Props

processing

NameTypeDescription
processingboolgives an indication of the process in progress.
server.processing ? "loading...." : <div>...</div>;

error(?key)

NameTypeDescription
errorboolget indication error by all or key.
...
server.error()
//
server.error('key')

message(key*)

NameTypeDescription
messagestringget message
...
server.message('key')

clear()

NameTypeDescription
clearfuncclear error.
...
server.clear()

cancel()

NameTypeDescription
cancelfunccancel request pending.
...
server.cancel()

validate(?option)

NameTypeDescription
validatefunccheck validation.
...
server.validate()
//or
server.validate({
    service: (event) => {
         fetch("http://example/validation", {method: 'post', body: event.data})
            .then((resp) => resp.json())
            .then((resp) => {
        event.parser(resp.error);
        });
    }
})
//or
server.validate({
    service: (data) =>  (event) => {
         fetch("http://example/validation", {method: 'post', body:data})
            .then((resp) => resp.json())
            .then((resp) => {
        event.parser(resp.error);
        });
    }
})
0.0.5

2 days ago

0.0.4

3 days ago

0.0.3

6 days ago

0.0.2

6 days ago

0.0.1

15 days ago

0.6.1

4 years ago

0.6.0

4 years ago

0.5.1

4 years ago

0.5.0

4 years ago

0.4.0

4 years ago

0.3.3

4 years ago

0.3.1

4 years ago

0.3.0

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago