// Created on savesnippets.com ยท https://savesnippets.com/KJvl3VZRYGkDik export function authedFetch(tokenSource: string | (() => string | Promise)) { return async (url: string, opts: RequestInit = {}): Promise => { const token = typeof tokenSource === 'function' ? await tokenSource() : tokenSource; return fetch(url, { ...opts, headers: { ...(opts.headers ?? {}), Authorization: `Bearer ${token}`, }, }); }; } const api = authedFetch(() => localStorage.getItem('access_token') ?? ''); const r = await api('/api/me'); const r2 = await api('/api/profile', { method: 'PUT', body: JSON.stringify(profile) });