Giter Club home page Giter Club logo

alova's People

Contributors

alexander-mart avatar allenli178 avatar changlin2569 avatar dependabot[bot] avatar fengren avatar jou-amjs avatar leinad59 avatar meetinaxd avatar panghujiajia avatar semantic-release-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alova's Issues

[Feature Request] GlobalFetch.ts 错误返回参数需要更丰富

你在什么情况下,需要这个功能解决什么问题?

// GlobalFetch.ts
//……
      response: () =>
        fetchPromise.then(
          response => {
            // 请求成功后清除中断处理
            clearTimeoutTimer(abortTimer);
            const { status, statusText } = response;
            return /^[2|3]/.test(status.toString())
              ? response
              : promiseReject(alovaError(statusText.toString(), status));
          },
          err => promiseReject(alovaError(isTimeout ? 'fetchError: network timeout' : err.message))
        ),
//……

这里错误信息返回statusText.toString() 只是http状态文本,不能当作前端的友好提示文本有啥意义?
假如接口在body 中有更详细的内容,你也把这块信息忽略了。

你期望的 API 是什么样子的?

希望

  1. 不要用alovaError 包裹,加了一层文字好丑。
  2. 错误信息要返回status code、status text、body 更友好。

[Bug Report] TypeScript 5无法导入alova类型声明文件

重现链接

https://github.com/Jon-a-than/vite-vue3-ts-alova

alova 版本

2.5.1

描述一下你遇到的问题。

导入alova时,TS警告

There are types at '/node_modules/alova/typings/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'alova' library may need to update its package.json or typings.ts(7016)

packages.jsonexports字段改为下面这样就可以正常导入

  "exports": {
    ".": {
      "types": "./typings/index.d.ts",
      "default": "./dist/alova.esm.js"
    },
    "./vue": {
      "types": "./typings/vuehook.d.ts",
      "default": "./dist/hooks/vuehook.esm.js"
    },
    "./react": {
      "types": "./typings/reacthook.d.ts",
      "default": "./dist/hooks/reacthook.esm.js"
    },
    "./svelte": {
      "types": "./typings/sveltehook.d.ts",
      "default": "./dist/hooks/sveltehook.esm.js"
    },
    "./GlobalFetch": {
      "types": "./typings/globalfetch.d.ts",
      "default": "./dist/adapter/globalfetch.esm.js"
    }
  },

重现步骤

  1. 使用TypeScript 5.0.4
  2. 使用Vscode打开/src/api.ts文件
import { createAlova } from 'alova'
import GlobalFetch from 'alova/GlobalFetch'
import VueHook from 'alova/vue'

export const alovaInstance = createAlova({
  statesHook: VueHook,

  requestAdapter: GlobalFetch(),

  responded: (response: Response) => response.json()
})

设备/浏览器/浏览器版本

No response

[Bug Report] uni-app支付宝小程序环境

Reproduction Link

empty

alova Version

2.1.1

Describe the Bug

image
image
image
image
我尝试改源码,只需要把self函数更名就可以解决
支付宝小程序环境,因为把self设置成readonly,所以编译不通过,微信小程序没有这种设置,所有没这个问题

Reproduce Steps

初始化项目
npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project

进入项目安装依赖
npm i

安装alova
npm install alova @alova/adapter-uniapp --save

在src/pages/index/index.vue下编写代码

<script setup lang="ts"> import { createAlova } from "alova"; import type { Method } from "alova"; import AdapterUniapp from "@alova/adapter-uniapp"; createAlova({ ...AdapterUniapp(), }); </script> 1111 运行代码 npm run dev:mp-alipay 打开支付宝小程序工具,打开项目目录dist\dev\mp-alipay,运行小程序就会出现这个问题

Device / Browser / Browser Version

支付宝小程序

[Bug Report] useFetcher cause cache data error

Reproduction Link

https://codesandbox.io/s/suspicious-rosalind-er2b82?file=/src/App.vue

alova Version

^2.1.2

Describe the Bug

Hi, I have a bug to report.

This example was copied from official Doc here:

https://alova.js.org/zh-CN/tutorial/learning/use-fetcher#%E9%A2%84%E5%8A%A0%E8%BD%BD%E6%95%B0%E6%8D%AE

Problem seems to be here:

onSuccess(() => {
  fetch(getTodoList(currentPage.value + 1));
});

It would cause alova.js to bring wrong data after page data is cached.

Reproduce Steps

  1. Click 3 pages to let alova.js cache the data.
  2. Click page 3
  3. Click page 2, nothing would happen.
  4. Click page 1, page 2 data will be shown.

Device / Browser / Browser Version

Chrome 112.0.5615.138

[Bug Report] 请求成功的拦截器throw抛出错误后,缓存不能清除。

重现链接

暂无

alova 版本

2.0.6

描述一下你遇到的问题。

const alovaInstance = createAlova({
  // ...
  responsed: {
    // 请求成功的拦截器
    onSuccess: async (response, method) => {
      if (response.status >= 400) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {

        //---此处拦截后,请求缓存会一直存在。
        //---比如第一次POST或PUT请求报错后,后续由于存在缓存一直无法重新请求
        throw new Error(json.message);


      }
      return json.data;
    },
    onError: (err, method) => {
      throw new Error(error.message);
    }
  }
});

重现步骤

  1. 请求编辑接口 (接口报错)
  2. alova请求拦截responsed,throw 抛出错误
  3. 修正编辑接口(接口正常)
  4. 再次请求编辑接口,仍报错。此时接口已恢复正常,刷新页面再请求就不报错,由此可见受缓存影响。

设备/浏览器/浏览器版本

MacOS Ventura 13.2.1/ Chrome 111.0.5563.64(正式版本) (x86_64)

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

[Bug Report] uniapp在微信小程序平台请求报错

重现链接

https://gitee.com/h_mo/uniapp-vue3-vite-ts-template

alova 版本

2.0.9

描述一下你遇到的问题。

按文档操作, 在微信小程序请求时报错,猜测是在请求成功的拦截器中 return data 这一步报错,H5没问题

image

// uni-app版本
"@dcloudio/uni-app": "3.0.0-alpha-3071220230324001"

重现步骤

打开 重现链接,运行项目:

关于->登录

设备/浏览器/浏览器版本

小程序开发工具(1.06.2303220win32-x64)

[Feature Request] responsed.onSuccess是否可以加上request

你在什么情况下,需要这个功能解决什么问题?

responsed.onSuccess只看到response和method,是否可以把request加上?用作一些客服端的判断透传;
比如说onSuccess里封装了统一的错误处理,但是在某些特定接口需要对错误进行定制化处理,通过request获取到对应的tag,则通用处理不执行。

你期望的 API 是什么样子的?

onSuccess(response, method, request) {
// ......
}

[Bug Report] 文档中的快速入门例子无法执行

重现链接

alova 版本

2.1.0

描述一下你遇到的问题。

`

Loading...
{{ error.message }}
responseData: {{ data.json()}} <script setup> import { createAlova, useRequest } from "alova" import GlobalFetch from "alova/GlobalFetch" import VueHook from "alova/vue" // 1. 创建alova实例 const alovaInstance = createAlova({ // VueHook用于创建ref状态,包括请求状态loading、响应数据data、请求错误对象error等 statesHook: VueHook, // 请求适配器,推荐使用fetch请求适配器 requestAdapter: GlobalFetch(), }) // 2. 使用alova实例创建method并传给useRequest即可发送请求 const { loading, data, error,onSuccess } = useRequest( alovaInstance.Get( "https://www.fastmock.site/mock/d1e86a30143876254ccbb72f6cd5d279/api/addons/ddrive/freight/carInfo", {} ) ) onSuccess((event) => { console.log("请求成功,响应数据为:", event.data) console.log("本次请求的method实例为:", event.method) console.log("响应数据是否来自缓存:", event.fromCache) }) </script>

`
页面显示 responseData: "[object Promise]"

重现步骤

设备/浏览器/浏览器版本

No response

[Feature Request]alova支持服务端渲染(SSR)

Reproduction Link

//这是一个alova的封装库
alova.ts
import { createAlova,useRequest } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import VueHook from 'alova/vue';

const alovaInstance = createAlova({
    baseURL:'/',
    timeout:1000 * 30,
    // vue项目传入VueHook,react项目传入ReactHook
    statesHook:VueHook,
    // 传一个请求适配器,GlobalFetch是我们提供的fetch api适配器
    requestAdapter: GlobalFetch(),
    // 请求拦截器
    beforeRequest(config) {
        console.log(config)
        // config.headers.token = '这里是测试token';
    },
    responsed:{
        // 请求成功的拦截器
        // 当使用GlobalFetch请求适配器时,第一个参数接收Response对象
        // 第二个参数为当前请求的method实例,你可以用它同步请求前后的配置信息
        onSuccess: async (response, method) => {
            if (response.status >= 400) {
                throw new Error(response.statusText);
            }
            const json = await response.json();
            if (json.code !== 200) {
                // 抛出错误或返回reject状态的Promise实例时,此请求将抛出错误
                throw new Error(json.message);
            }

            // 解析的响应数据将传给method实例的transformData钩子函数,这些函数将在后续讲解
            return json.data;
        },

        // 请求失败的拦截器
        // 请求错误时将会进入该拦截器。
        // 第二个参数为当前请求的method实例,你可以用它同步请求前后的配置信息
        onError: (err, method) => {
            alert(err.message);
        }
    }
})
export default alovaInstance
//这是一个调用库
about.ts
import { useRequest } from 'alova';
import alovaInstance from '@/api/alova'

export const testSend = (data:object)=>{
    return useRequest(
        alovaInstance.Get('https://api.alovajs.org/profile', {
          params: {
            id: 1
          }
        })
    )
}
//这是一个调用库

alova Version

2.1.1

Describe the Bug

在 vite + vue3里面使用会报错
并且在ssr渲染模式下面,会编译失败,并不能找到 import.mate

Reproduce Steps

使用 ssr + vite + vue3 的编译模式会错误

alova doesn't appear to be written in CJS, but also doesn't appear to be a valid ES module (i.e. it doesn't have "type": "module" or an .mjs extension for the entry point). Please contact the package author to fix.
Alova似乎并未写在CJS中,但似乎并不是有效的ES模块(即它没有“类型”:“模块”或输入点的.MJS扩展名)。请联系包裹作者修复。

Device / Browser / Browser Version

No response

[Bug Report] 在responsed 的 onSuccess 钩子函数内抛错无法被 onError 捕获

重现链接

https://codesandbox.io/p/sandbox/vigilant-grothendieck-lr4qxj?file=%2Fsrc%2Fapi.js&selection=%5B%7B%22endColumn%22%3A42%2C%22endLineNumber%22%3A18%2C%22startColumn%22%3A42%2C%22startLineNumber%22%3A18%7D%5D

alova 版本

2.1.0

描述一下你遇到的问题。

onSuccess内抛错无法被onError捕获

  responsed: {
    onSuccess: (response: any) => {
      console.log("onSuccess", response)
      throw new Error("onSuccess")
      // return (response as any).json()
    },
    onError: (response) => {
      console.log("onError", response)
      throw new Error("onError")
    }
  }

重现步骤

  • 请求接口
  • onSuccess 钩子函数 throw new Error 抛出错误
  • 未进入 onError 钩子函数

设备/浏览器/浏览器版本

Microsoft Edge 版本 112.0.1722.39 (正式版本) (64 位)

[Bug Report] 分页时,清除缓存只能清除当前分页,其他页未清除。

重现链接

暂无

alova 版本

2.0.3

描述一下你遇到的问题。

加载分页列表。清除缓存只能清除当前分页,其他页未清除。
失效缓存方式都测试过了,结果相同。
以下是测试失效缓存方式

  1. 方式1:invalidateCache('list')
  2. 方式2:invalidateCache(/list/)
  3. 方式3:invalidateCache({name: 'list', filter:()=>true})
  4. 方式4: 配置 hitSource: /list/

重现步骤

比如有3页,总数据28条。

  1. 连续点1、2、3页让缓存生效。
  2. 在第3页删除一条数据并失效缓存
  3. 调用列表接口(第3页缓存失效成功,显示27条)
  4. 在点第1页或第2页,总数据还是显示28条。

设备/浏览器/浏览器版本

No response

[Bug Report] cors response

Reproduction Link

https://github.com/IdrissGarfa/react-alova

alova Version

v2.0.16

Describe the Bug

I'm trying to test alova with react js 18.2 using vite 4.2. whenever i made a get request to a local api [localhost:3000/quotes] I get a response with [type: cors] without data! I have done many searches about cors in client side but i didn't get any solutions
alova

Reproduce Steps

alova

Device / Browser / Browser Version

Google Chrome

希望能加强TS提示

你在什么情况下,需要这个功能解决什么问题?

const { data, loading, send } = useRequest((query: { q: number }) => doTest(query), { initialData: "", immediate: false, })

目前send类型是(...args: any[]) => Promise<unknown>,期望得到准确的提示:({q:number})=>Prmise</*...*/>

你期望的 API 是什么样子的?

希望得到更好的ts提示

如何在纯 html 内用呢?

Discussed in #19

Originally posted by jufjzq March 31, 2023

<script src="https://unpkg.com/alova/dist/alova.umd.min.js"></script>
<script src="https://unpkg.com/alova/dist/adapter/globalfetch.umd.min.js"></script>

<script>
  const alovaInstance = alova.createAlova({
    baseURL: 'localhost:3000',
    requestAdapter: window.GlobalFetch(),
  });
  const { data, loading, error } = alova.useRequest(
    () => alovaInstance.Get('/api'),
    {
      initialData: [],
    }
  )
  console.log(data);
</script>

F12报错

Uncaught TypeError: Cannot destructure property 'create' of 'm(...)' as it is undefined.
    at fe (alova.umd.min.js:1:6750)
    at e.useRequest (alova.umd.min.js:1:8881)
    at (索引):44:42
```</div>

useRequest 返回的 data 类型支持使用 transformData 的 ReturnType

你在什么情况下,需要这个功能解决什么问题?

interface Todo {
  title: string;
  time: string;
  done: boolean;
}
const Get = alovaInstance.Get('/todo/list', {
  // 将类型写到data参数中,而headers会自动推断,可以不用指定类型
  transformData(data: Todo[], headers) {
    return data.map(item => ({
      ...item,
      status: item.done ? '已完成' : '未完成'
    }));
  }
});

const { data } = useRequest(Get);
// vue: data的类型为Ref<(Todo & { status: string })[]>
// react: data的类型为(Todo & { status: string })[]
// svelte: data的类型为Writable<(Todo & { status: string })[]>

感觉直接使用 transformData 的 ReturnType 比取 transformData 的参数会更自由点,因为一般只会定义 transformData 后的类型,不会定义 transformData 数据前的类型,而且也不太关心转换之前的数据类型是什么样子,个人感觉。

你期望的 API 是什么样子的?

transformData 使用 ReturnType 作为类型返回

[Feature Request]OpenApi的支持

你在什么情况下,需要这个功能解决什么问题?

解决在编写对应的 openapi 后,可以根据yaml生成对应的请求api,无感切换到 alova

你期望的 API 是什么样子的?

类似于 openapi-typescript-axios 这样可以根据 api 自动生成对应请求代码的功能

[Bug Report]设置全局请求拦截器后 invalidateCache('List') 不能清除缓存

重现链接

暂无

alova 版本

2.0.0

描述一下你遇到的问题。

const list = params => alovaInstance.Get('/ad', { name: 'List', params })

//……

const del = id => alovaInstance.Delete('/ad/del/' + id)
const { send, onComplete } = useRequest(id => del(id),{
      immediate: false
})
onComplete(() => {
  //invalidateCache()        //没问题。
  invalidateCache('List')  // 不生效,缓存未清除
})

invalidateCache() 传其他参数也无效(例如正则、对象)。

重现步骤

  1. 设置获取列表接口 alovaInstance.Get 名称为 'List'
  2. 添加、编辑、删除 完成时调用 invalidateCache('List') 清除缓存
  3. send 调用获取列表接口

设备/浏览器/浏览器版本

Mac Ventura v13.2.1/Google Chrome v110.0.5481.177

响应数据的返回类型定义

          还有这个(2.5.2):

image
image

而且useRequest如果要泛型加持,好像需要传入7个泛型。。而最关注的无非就是一个返回值类型,是否能够,达到只传一个返回值类型,比如useRequest<string>, 或useRequset<Record<string,any>>,或useRequset<boolean>,唯一的一个泛型,就是data返回值的类型~

Originally posted by @kenixFog in #91 (comment)

[Bug Report] taro适配器 vue3

重现链接

https://github.com/HuangYaobin/taro-alova-demo

alova 版本

2.4.1

描述一下你遇到的问题。

按照文档配置, 没有响应式。

import { createAlova } from 'alova';
import AdapterTaroVue from '@alova/adapter-taro/vue';

const alovaInst = createAlova({
  baseURL: 'https://api.alovajs.org',
  ...AdapterTaroVue()
});

需要加一行配置,才有响应式。

import { createAlova } from 'alova';
import AdapterTaroVue from '@alova/adapter-taro/vue';
import VueHook from 'alova/vue';

const alovaInst = createAlova({
  baseURL: 'https://api.alovajs.org',
  ...AdapterTaroVue(),
  statesHook: VueHook
});

image

loading和data变化,watchEffect监听不到。

重现步骤

点击button

设备/浏览器/浏览器版本

No response

[Feature Request] 提供一种公共状态管理的数据获取方式

In what situation do you need this function to solve the problem?

想问下,那用这个alova,公共状态管理咋办呢,每个想公共状态管理的都对data加个watch么?有没有更优雅的方式呢呀

What do you expect the API to look like?

提供一种公共状态管理的数据获取方式

[Bug Report] immediate:false in useRequest doesn't seem to work

Reproduction Link

https://codesandbox.io/p/sandbox/alova-immediate-forked-ocb5tf?file=%2Fsrc%2FApp.tsx

alova Version

2.5.4

Describe the Bug

Hi, I'm loving this library and slowly migrating my code from Axios to Alova. I came across one issue, which I'm not sure is a bug or not.

On React, using useRequest with the parameter immediate: false doesn't seem to work for me. The request call is always fired when the page is loaded. This happens on both using a requestAdapter of xhrRequestAdapter() and GlobalFetch().

I can create a sandbox and try and reproduce, but before doing that I wondered whether if this is known issue at all?

Reproduce Steps

When loading the page, all useRequests are fired, even if the immediate flag is set to false.

Device / Browser / Browser Version

on all browsers I tested (edge/chrome/safari)

在Chrome58下报AbortController未定义错误

你在什么情况下,需要这个功能解决什么问题?

运行环境受限,chrome 58

经过验证,发现其中AbortController 无法被兼容,关于这个场景有没有可替代方案。。

image

image

你期望的 API 是什么样子的?

请问作者有讨论群之类的吗?

你在什么情况下,需要这个功能解决什么问题?

请问作者有讨论群之类的吗?

你期望的 API 是什么样子的?

请问作者有讨论群之类的吗?

原生小程序支持吗

In what situation do you need this function to solve the problem?

原生小程序支持吗

What do you expect the API to look like?

原生小程序支持吗

[Bug Report] 官方文档文案错误。

重现链接

https://alova.js.org/zh-CN/overview/installation/

alova 版本

1.4.0

描述一下你遇到的问题。

概览》安装/使用》引入 fetch adapter 中有一文案错误:
“你可以通过window.GlobalFetch使用,它将使用winfow.fetch进行请求。” 中的winfow.fetch中单词window拼写错误

重现步骤

  1. 打开链接 https://alova.js.org/zh-CN/overview/installation/
  2. 找到 “引入 fetch adapter ”章节

设备/浏览器/浏览器版本

No response

[Bug Report] ntime-core.esm-bundler.js:40 [Vue warn]: onUnmounted is called when there is no active component instance to be associated with.

Reproduction Link

alova Version

2.1.2

Describe the Bug

Whenever I navigate between pages, I get this error.

Unmounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

Looks like the problem is here:

effectRequest({ handler, removeStates, immediate, watchingStates }) {
// 组件卸载时移除对应状态
onUnmounted(removeStates);
immediate && handler();
let timer;
forEach(watchingStates || [], (state, i) => {
watch(state, () => {
timer && clearTimeoutTimer(timer);
timer = setTimeoutFn(() => {
handler(i);
timer = undefinedValue;
});
}, { deep: trueValue });
});
}

Reproduce Steps

Install the library and use it in pinia store to perform the network operations and observe the error.

Note: Alova library is not imported in the component level. It is being used by pinia stores.

Device / Browser / Browser Version

No response

[Feature Request] 如何像Axios一样无痛刷新Token

你在什么情况下,需要这个功能解决什么问题?

刷新token之后发现原来的请求Token还是旧的,得第二次发送请求才能生效,如何拦截后就新的Token立即生效,代码如下:

beforeRequest: (method) => {
            if (getCache(TOKEN_KEY) == null) { //Token过期
                new Promise(resolve => {
                    const token = authStore.getRefreshToken;
                    const { send: sendRefreshToken } = useRequest(refreshToken, { immediate: false });
                    sendRefreshToken({ refreshToken: token })
                        .then((res) => {
                            if (res.success) {
                                authStore.setToken(res);
                                method.config.headers = assign(method.config.headers, authStore.getAuthorization);
                                resolve(method);
                            }
                        });
                });
            } 
    },

你期望的 API 是什么样子的?

beforeRequest中刷新Token,method.config.headers中Token可以立即更新

[Bug Report] invalidateCache不传参数时无法清除持久化数据

重现链接

~~

alova 版本

2.5.1

描述一下你遇到的问题。

invalidateCache,好像对持久化缓存策略不生效,执行完,缓存依旧生效;对内存模式好像没问题

重现步骤

1、测试环境,缓存3分钟,然后有个全局定时器,每1分钟执行一次invalidateCache()
2、memory下,定时器执行完,再次请求,会发起请求;restore模式下,定时器执行完,再次请求,缓存依旧有效

3、观察了下大概是因为invalidateCache并没有针对localStorage中数据进行清除操作

或者说如果invalidateCache的设计只是针对memory模式,是否可以提供针对restore的全局缓存清理接口~~

设备/浏览器/浏览器版本

No response

请问如何在onSuccess/onError内重新发起当前的请求?

你在什么情况下,需要这个功能解决什么问题?

比如登录的acess_token过期的情况下,通过refresh_token刷新access_token并重新发起请求返回数据

你期望的 API 是什么样子的?

import { refreshToken } from 'token'
const alovaInstance = createAlova({
    baseURL: BASE_URL,
    ...AdapterUniapp({}),
    timeout: 5000,
    beforeRequest: (method) => {
        const authStore = useAuthStore();
        method.config.headers = assign(method.config.headers, HEADER, authStore.getAuthorization);
    },
    responsed: {
        /**
         * 请求成功的拦截器
         * 第二个参数为当前请求的method实例,你可以用它同步请求前后的配置信息
         * @param response
         * @param method
         */
        onSuccess: async (response, method, reload) => {
            const { statusCode, data: rawData } = response;
            const { code, message, data } = rawData as API;
            if (statusCode === 200) {
                if (code === ResultEnum.SUCCESS) {
                    return data;
                } else  if (code === ResultEnum.TOKEN_EXPIRED) {
                    await refreshToken();
                    const resData= await reload();
                    return reData;
                } 
                message && Toast(message);
                return Promise.reject(rawData);
            }
            checkStatus(statusCode, message || '');
            return Promise.reject(rawData);
        },
    },
});

[Feature Request] 异常处理机制

你在什么情况下,需要这个功能解决什么问题?

1、感觉目前的异常机制有些不完备
① responded中 onSuccess 抛出的异常,无法被responded中 onError捕获
② responded中 onSuccess 抛出的异常,可以被useRequest提供的 onError回调捕获,却无法通过useRequest提供的 error获取
③ beforeRequest 中抛出的异常,既无法被responded中 onError捕获,也无法通过useRequest提供的 onError回调捕获,也无
法通过error获取
2、这样,就可能需要再单独的请求体外增加try...catch,增加使用成本

你期望的 API 是什么样子的?

1、拿异常来说,封装程度越高,越友好,使用者不需要关心是哪个环节的出了异常
2、只要useRequest或useWatcher过程中发生了异常,不论是在beforeRequest,还是responded中的onSuccess 、onError甚至其它环节的业务中抛了异常,对于使用者而言,最好能通过useRequest提供的error和onError获取到
3、至少提供钩子函数可以对异常可以统一处理(这样有便于针对具体业务,对alova进行简单的二次封装),在统一异常的处理钩子函数中(可以存在默认处理方式,比如抛出异常),也可覆写,可以自行进行业务处理(日志、提示信息等后),选择继续抛出异常,或return 或不做任何处理:
① 如果抛出异常(可做为alova默认处理机制),则可以被useRequest等提供的error和onError获取
② return ***,则表示整个请求过程存在返回结果,结果可根据业务自定定义,用于data结果值
③ 不做任何处理的,可在method中增加defaultData(或者可沿用iniatData)作为data结果值,

[Bug Report] 使用usePagination分页时,watchingStates没有设置、或者为空数组的情况下,改变请求中的某一个参数,会触发多次请求,page参数也会改变

Reproduction Link

暂无

alova Version

"alova": "^2.0.16", "@alova/scene-vue": "^1.0.4"

Describe the Bug

import { ref } from 'vue'
import { usePagination } from "@alova/scene-vue"
import { get_news_page_hot_info } from "@/api"
import type { HomeTabType, NewsType } from "@/models"
const { tabInfo } = defineProps<{tabInfo: HomeTabType}>()
const newId = ref<number>(0)
const {
  loading, data, isLastPage, page
} = usePagination((page) =>
  get_news_page_hot_info({
    firstFlag: page === 1 ? 1 : 0,
    newId: newId.value,
    hotListId: 0,
    videoId: 0,
    pageNo: page,
    businessType: 1,
    subclass: tabInfo.subclass == '全部' ? '' : tabInfo.subclass
  }),
  {
    append: true,
    initialData: [],
    debounce: [500],
    preloadNextPage: false,
  }
)
const loadMore = () => {
  if (!loading.value && !isLastPage.value) {
    newId.value = data.value[data.value.length - 1].newsCollectInfo.newInfo.newId
    page.value++
  }
}

Reproduce Steps

暂无

Device / Browser / Browser Version

No response

[Feature Request] StorageAdapter支持异步存储

你在什么情况下,需要这个功能解决什么问题?

我想用localStorage作为StorageAdapter,但是localStorage默认使用的存储是indexDB,存储API是异步的。
const customStorageAdapter = {
async set(key, value) {
await localForage.setItem(key, value)
},
async get(key) {
return await localForage.getItem(key)
},
async remove(key) {
await localForage.removeItem(key)
}
}
在读取时发生了错误,
Uncaught (in promise) TypeError: storagedData is not iterable,
发生错误的地方是:
/**

  • 获取存储的响应数据
  • @param namespace 命名空间
  • @param key 存储的key
  • @param storage 存储对象
  • @param tag 存储标签,标记改变了数据将会失效
    */
    const getPersistentResponse = (namespace, key, storage, tag = null) => {
    const storagedData = storage.get(buildNamespacedStorageKey(namespace, key));
    if (storagedData) {
    const [response, expireTimestamp, storedTag = nullValue] = storagedData;
    // 如果没有过期时间则表示数据永不过期,否则需要判断是否过期
    if (storedTag === tag && (!expireTimestamp || expireTimestamp > getTime())) {
    return response;
    }
    // 如果过期,则删除缓存
    removePersistentResponse(namespace, key, storage);
    }
    };

你期望的 API 是什么样子的?

希望StorageAdapter可以支持异步

AxiosRequestAdapter used, ts reported an error

Reproduction Link

null

alova Version

2.5.0

Describe the Bug

const useAlova = createAlova({
  baseURL: import.meta.env.VITE_APP_API_BASEURL,
  statesHook: VueHook,
  requestAdapter: axiosRequestAdapter(), 
  timeout: DEFAULT_TIME_OUT,
  responded: {
    onSuccess: handleResponseSuccess,
    onError: handleResponseFail,
  },
})

AxiosRequestAdapter used, ts reported an error, If we switch to GlobalFetch, there's no problem

[ts error]  Exported variable 'useAlova' has or is using name 'RawAxiosHeaders' from external module "e:/*****/node_modules/axios/index" but cannot be named.

Reproduce Steps

AxiosRequestAdapter used, ts reported an error, If we switch to GlobalFetch, there's no problem

[TS ERROR]:  Exported variable 'useAlova' has or is using name 'RawAxiosHeaders' from external module "e:/*****/node_modules/axios/index" but cannot be named.

Device / Browser / Browser Version

No response

[Feature Request] 建议 useRequest 参数和 ahooks 对齐

你在什么情况下,需要这个功能解决什么问题?

如果 useRequest 是参考的 ahooks 里的useRequest做的话,似乎没必要把相关的参数名给调整了,统一的话,更好一些。

你期望的 API 是什么样子的?

const { loading, run, runAsync } = useRequest(service, {
manual: true
});

[Bug Report] alova实例问题

重现链接

~~

alova 版本

1.4.0

描述一下你遇到的问题。

alova实例问题

<script setup lang="ts">
import { createAlova, useRequest } from 'alova'
import { NButton } from 'naive-ui'
import VueHook from 'alova/vue'
import { createAlovaMockAdapter, defineMock } from '@alova/mock'

defineOptions({ name: 'AlovaSecond' })

// mock data
const mockData = defineMock({
  '/list': ['apple', 'banana', 'orange'],
  '[POST]/save': () => {
    return {
      msg: 'success',
    }
  },
})

function getAlova() {
  return createAlova({
    baseURL: 'http://example.com',
    statesHook: VueHook,
    timeout: 5000,
    requestAdapter: createAlovaMockAdapter([mockData], { delay: 1500 }),
    responsed: response => response.json(),
  })
}

// const instance = createAlova({
//   baseURL: 'http://example.com',
//   statesHook: VueHook,
//   timeout: 5000,
//   requestAdapter: createAlovaMockAdapter([mockData], { delay: 1500 }),
//   responsed: response => response.json(),
// })

const saveData = name => getAlova().Post('/save', { name }, { localCache: 0 })

const {
  data: data2,
  loading: loading2,
  error: error2,
  send: send2,
} = useRequest(() => saveData('alova'), {
  initialData: {},
  immediate: false,
})
</script>

<template>
  <n-space vertical flex-center>
    <NButton :loading="loading2" @click="send2">
      save data
    </NButton>
    <span v-if="error2">{{ error2.message }}</span>
    <div v-else>
      {{ data2 }}
    </div>
  </n-space>
</template>

页面加载失败,原因
image

重现步骤

放开注释部分,则正常~

1、不晓得是否是有意而为之~感觉不太合理,必须先有一个alova实例,但是实际请求时用的却是另一个实例~~

设备/浏览器/浏览器版本

No response

localCache只有在设置为0时才能拉取成功吗?

Reproduction Link

alova Version

2.5.0

Describe the Bug

请问在使用 fetch 数据拉取的时候,对应的接口实例,要设置 localCache: 0,才能拉取成功,我实际使用中,发现不设置localCache: 0 是不会去重新拉取的。想问下是这样的吗?

Reproduce Steps

举例:

export const getActivityDetailApi = (activityId) => {
  return alovaInstance.Get(
    `******/${activityId}`,
    {
      localCache: 0
    }
  );
}

// 调用:
fetch(getActivityDetailApi(1));

Device / Browser / Browser Version

uniapp、vue3

[Bug Report] 请求共享在请求超时的情况下的混乱问题

In what situation do you need this function to solve the problem?

PS: 不清楚是不是使用方式有误~~

使用场景
1、2个按钮A、 B,对应请求A1、B1,其中A1直接响应,B1延迟10秒~~全局超时时间5秒(B1肯定超时)
2、单独点击按钮并等待各请求完成响应,A1正常,B1超时,没问题
3、点击B按钮,再点击A按钮,A的加载状态跟B按钮保持同步,并且结果也显示超时,无法正常获取结果

猜测是不是useRequest内部处理有问题?或者使用上需要注意什么?

What do you expect the API to look like?

1、各请求的状态、结果等应该不受影响

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.