如何在React Query和Axios中使用自定义选项创建可重用的查询函数?

uoifb46i  于 2024-01-07  发布在  iOS
关注(0)|答案(1)|浏览(112)

我正在使用React Query和Axios处理API请求。目前,我有一个函数registerByEmail,它使用Axios处理注册,并为mutation定义了一个useRegisterByEmail钩子。下面是现有的设置:

export interface ApiResponseInterface<T> {
  status: string
  statusCode: number
  result: T
}

export interface ErrorApiResponseInterface {
  statusCode: number
  error: string
  message: string[]
}

export interface RegisterByEmailBodyInterface {
  email: string
  username: string
  password: string
}

export interface RegisterByEmailResultInterface {}

export const registerByEmail = async (body: RegisterByEmailBodyInterface) => {
  return await axios.post<ApiResponseInterface<RegisterByEmailResultInterface>>(
    "/auth/email/register",
    body
  )
}

export const useRegisterByEmail = () =>
  useMutation({
    mutationFn: registerByEmail,
    mutationKey: ["register"],
  })

字符串
现在,我的目标是通过允许传入自定义选项来使useRegisterByEmail钩子更加通用。下面是所需的修改:

export const useRegisterByEmail = (options) =>
  useMutation({
    mutationFn: registerByEmail,
    mutationKey: ["register"],
    ...options
  })


如何在确保正确键入和处理useRegisterByEmail钩子中的选项的同时实现此修改?我特别希望通过有效地合并可定制选项来增强其可重用性。
我非常感谢任何见解或例子证明正确的方法来实现这一点。谢谢!

r55awzrz

r55awzrz1#

你可以用我的:

// Api.ts
import config from './Global'

const Api = {
  post: (route: any, data: any, conf: any) => {
    return config.axiosHandle().post(`${route}`, data, conf)
  },
  delete: (route: any, conf: any) => {
    return config.axiosHandle().delete(`${route}`, conf)
  },
  get: (route: any, dataCom = '', conf: any) => {
    const data = dataCom
    const qs =
      '?' +
      Object.keys(data)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[+key])}`)
        .join('&')

    return config.axiosHandle().get(`${route}${dataCom !== '' ? qs : ''}`, conf)
  }
}

export default Api
// Global.ts
import axios from 'axios'
import Cookies from 'js-cookie'

const config = {
  udata: Cookies.get('token'),
  axiosHandle: () => {
    return axios.create({
      baseURL: '',
      validateStatus: function (status: any) {
        if (status === 401) localStorage.clear()

        return status >= 200 && status < 300
      },
      headers: config.udata
        ? {
          Authorization: 'Bearer ' + config.udata
        }
        : {}
    })
  }
}
export default config
// Request.ts
import Api from './Api'

export const MerchantsRequest = (shopId: string, fn: (arg0: any) => void) => {
  Api.get(`/api/Merchants/GetMerchantListFilterId?ShopId=${shopId}`, '', '')
    .then((response: any) => {
      fn(response.data.result.dbData)
    })
    .catch(err => console.log(err))
}

你可以像这样使用它:

useEffect(() => {
    if (merchant != undefined)
      MerchantsRequest(merchant, x => {
        setIsLoading(false)

        setMerchants(x)
      })
  }, [merchant])

相关问题