Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Request option onFirst. #234

Open
s3xysteak opened this issue Apr 22, 2024 · 1 comment
Open

[Feature Request] Request option onFirst. #234

s3xysteak opened this issue Apr 22, 2024 · 1 comment

Comments

@s3xysteak
Copy link

s3xysteak commented Apr 22, 2024

需求描述 Feature Description

比方说,我希望在第一次返回请求结果时给某个变量赋予一个初始值,我一般使用 vueuse 的一个函数以方便的实现这个效果。

const active = ref()
const { data } = useRequest(api)
watchOnce(data, (res) => {
  active.value = res[0]
})

但大量的这种行为是繁琐的,我想这应该是一个常见的需求,因此希望轮子能自带这方面的支持,api看起来像这样:

const active = ref()
useRequest(api, { onFirst: data => { active.value = data[0] } })

建议的解决方案 Proposed Solution

let isFirst = true

// 假设处理请求的方法叫做execute
function execute() {
// ...
  const _onFirst = () => {
    onFirst()
    isFirst = false
  }
  isFirst && _onFirst()
  // ... 
}

其他信息 Other information

@chuxiaoguo
Copy link

chuxiaoguo commented Apr 28, 2024

你可以自行写一个插件,类似这样的:

export const onFistPlugin =  definePlugin((queryInstance, options) => {
  const isFist = ref(true)
  return {
    onSuccess(data) {
      if (!isFist.value) {
        return
      }
      options.onFirst?.(data)
      isFist.value = false
    }
  }
})

 --- example ---
useRequest(api, {
  onFirst: data => { active.value = data[0] }
}, [onFistPlugin])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants