1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import { message } from 'antd'
- import { useState } from 'react'
- export interface AjaxPromise {
-
- run: (params?: any) => Promise<any>,
-
- refresh: () => Promise<any>,
-
- mutate: (data: any) => void
-
- initData: () => void,
-
- loading: boolean,
-
- data: any,
- }
- export function useAjax(fnc: (params?: any) => Promise<any>, options?: { type: 'table' | "noPage" }): AjaxPromise {
-
- const [loading, setLoding] = useState(false)
- const [data, setData] = useState<any>()
- const [oldParams, setOldParasm] = useState()
- async function run(params?: any) {
- setLoding(() => true)
- setOldParasm(() => params)
-
- if (options?.type === 'table') {
- params.pageNum = params.current
- delete params.current
- }
- return fnc(params).then(res => {
- setLoding(() => false)
- setData(() => res)
- if (res?.code === 500) {
- message.error(res?.msg)
- return res
- }
- if (options?.type === 'table') {
- return {
- data: res.data.records,
- total: res.data.total,
- current: res.data.current,
- pageSize: res.data.size,
- success: res.success
- }
- }
- if(options?.type === 'noPage'){
- return {
- current: 1,
- data: res.data,
- pageSize: 20,
- total: res.data.length,
- success: true
- }
- }
- return res
- }).catch(err => {
- console.log(err)
- setLoding(() => false)
- return err
- })
- }
- async function refresh() {
- setLoding(() => true)
- return fnc(oldParams).then(res => {
- setLoding(() => false)
- setData(() => res)
- return res
- })
- }
- async function initData() {
- setData(null)
- }
-
- async function mutate(data: any) {
- setData(data)
- }
- return { loading, data, run, refresh, initData, mutate }
- }
|