How can i async await in setting fetchOptions in a createClient function in urql

208 Views Asked by At

I want to fetch the token from async-storage but it returns a Promise of type string or undefined. Since fetchOptions is a function that returns a object of type RequestInit here is what i've tried

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

But typescript is not happy with me. How can I wake around this??

1

There are 1 best solutions below

0
On

Best options is to put this in an async function and call get token first, that's what I do in tests for example:

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

  client = new Client({
    url: 'http://localhost:4000/',
    exchanges: [cacheExchange, fetchExchange],
    fetchOptions: () => {
      return {
        headers: { authorization: token ? `Bearer ${token}` : '' },
      };
    },
  })
})