如何使用异步存储Axios

时间:2019-10-11 11:36:22

标签: react-native axios

问题:

我已经创建了react-native应用程序,并且我正在将AsyncStorage与axios一起使用来处理我的API调用。

import axios from "axios";
import { AsyncStorage } from "react-native";

// TODO: Replace this with actual JWT token from Keycloak
axios.defaults.headers.post["Content-Type"] = "application/json";

// Create axios instance for api calls
var instance = null;

export const setAuth = async () => {
  const user = await AsyncStorage.getItem("jwt");
  AsyncStorage.getItem("jwt").then(token => {
    instance = axios.create({
      baseURL: "",
      timeout: 150000,
      headers: {
        Authorization: "Bearer " + token,
        "Content-Type": "application/json"
      }
    });
    instance.interceptors.response.use(
      function(response) {
        return response;
      },
      async function(error) {
        if (error.response.status) {
          return error;
        }
      }
    );
  });
};

export const Get = (route, data) => {
  instance || setAuth();
  return instance.get(
    route,
    data == null ? { data: {} } : { data: JSON.stringify(data) }
  );
};

export const Post = (route, data) => {
  instance || setAuth();
  return instance.post(route, JSON.stringify(data));
};

export const Put = (route, data) => {
  debugger;
  instance || setAuth();
  return instance.put(route, JSON.stringify(data));
};

export const AddAdmin = (route, data) => {};

由于AsyncStorage的asynchronus属性,它没有创建axios instanceinstance = axios.create({。问题出在这行之后。所以有人可以帮我这个忙。我不知道有什么问题这个。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试一下。

export const setAuth = async () => {
  const token = await AsyncStorage.getItem('jwt');
  instance = axios.create({
    baseURL: '',
    timeout: 150000,
    headers: {
      Authorization: 'Bearer ' + token,
      'Content-Type': 'application/json'
    }
  });
   // remaining Code
};

export const Get = (route, data) => {
  function getData(){
     return instance.get(
      route,
      data == null ? { data: {} } : { data: JSON.stringify(data) }
    )
  }
  if(instance) return getData()
  return setAuth().then(getData)
}