LoginSignup
0
0

More than 1 year has passed since last update.

LocalStorageとaxiosインスタンスを「async await」で非同期にする方法

Last updated at Posted at 2021-11-24

export const accessTokenKey: string = 'access_token';

export const asyncLocalStorage = {
    setItem: async (value: string) => {
        await null;
        localStorage.setItem(accessTokenKey, value);
    },
    getItem: async () => {
        await null;
        return localStorage.getItem(accessTokenKey);
    },
    removeItem: async () => {
        await null;
        return localStorage.removeItem(accessTokenKey)
    }
};

export const asyncApiClient = {
  create: async () => {
    return await axios.create({
      baseURL: "http://localhost:8000/api",
      responseType: "json",
      headers: {
        "Content-Type": "application/json",
        Accept: 'application/json',
        "Authorization": `Bearer ${await asyncLocalStorage.getItem()}`
      },
    });
  }
}

使い方

await asyncLocalStorage.setItem(value)
await asyncLocalStorage.getItem()
await asyncLocalStorage.removeItem()

const apiClient = await asyncApiClient.create()
const res = await apiClient.get<ProductsModel[]>('/products/');
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0