我如何在urql中的createClient函数中异步等待设置fetchOptions

问题描述 投票:0回答:1

我想从

token
获取
async-storage
,但它返回
Promise
string
类型的
undefined
。由于
fetchOptions
是一个返回
RequestInit
类型的对象的函数,这是我尝试过的

export const client = createClient({
  url,
  fetchOptions: async () => {
    const token = (await retrieve(TOKEN_KEY)) ?? "";
    return {
      credentials: "include",
      headers: { authorization: token ? `Bearer ${token}` : "" },
    };
  },
});

但是 typescript 对我不满意。我怎样才能醒来??

urql react-async
1个回答
0
投票

最好的选择是将其放入异步函数中并首先调用获取令牌,这就是我在测试中所做的示例:

beforeEach(async () => {
  const token = await getToken()

  client = new Client({
    url: 'http://localhost:4000/',
    exchanges: [cacheExchange, fetchExchange],
    fetchOptions: () => {
      return {
        headers: { authorization: token ? `Bearer ${token}` : '' },
      };
    },
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.