不转换为异步功能就无法从函数内部的本地存储中获取价值

我为react-native中的API调用做了一个fetch函数的包装器。我不想在每次进行API调用时都传递JWT令牌,因此我认为在包装器中获取它会为我解决这个问题,但由于异步特性,我无法使其正常工作...

useFetch.js

// import qs from "querystring";
import { getUserAuthToken } from "../storage";

const responseChecker = async (response) => {
  let error = "";
  let data = {};
  let statusCode = null;
  if (!response.ok) {
    error = "Something went wrong";
    statusCode = response.status;
  } else {
    statusCode = response.status;
    data = await response.json();
  }
  return { statusCode, error, data };
};

const fetchAuthToken = getUserAuthToken();

const useFetch = (baseURL, authHeader = null) => {
  console.log(fetchAuthToken);
  **//Cannot get this token in time for the API call ^**
  const defaultHeader = {
    Accept: "application/json",
    "Content-Type": "application/x-www-form-urlencoded",
    key: "1c419c7e-3a34-49f0-9192-b48d4534dff3",
    Authorization: authHeader ? authHeader :fetchAuthToken,
  };

  const customFetch = (
    url,
    method = "GET",
    body = false,
    headers = defaultHeader,
  ) => {
    const options = {
      method,
      headers,
      credentials: "include",
    };
    if (body) options.body = body;
    return fetch(url, options);
  };
  const get = async (endpoint) => {
    const url = `${baseURL}${endpoint}`;
    const response = await customFetch(url, "GET");
    return responseChecker(response);
  };
  const post = async (endpoint, body = {}) => {
    const url = `${baseURL}${endpoint}`;
    const response = await customFetch(url, "POST", body);
    return responseChecker(response);
  };
  const put = async (endpoint, body = {}) => {
    const url = `${baseURL}${endpoint}`;
    const response = await customFetch(url, "PUT", body);
    return responseChecker(response);
  };
  return {
    get,
    post,
    put,
  };
};
export default useFetch;

storage.js

import AsyncStorage from "@react-native-community/async-storage";
export const getUserAuthToken = async () => {
  try {
    const userToken = await AsyncStorage.getItem("userAuthToken");
    return userToken;
  } catch (e) {
    console.log("error");
  }
};

exportAPI.js

import useFetch from "./fetch";
const LOCAL_IP = "192.168.0.131";
export const authAPI = (header) => useFetch(`http://${LOCAL_IP}:8000`, header);
export const activityAPI = useFetch(`http://${LOCAL_IP}:8000`);

Steps.js

import React, { useEffect, useState } from "react";
import { Text, Platform } from "react-native";
import { CardXLarge } from "../../../components/Cards/";
import fitnessKitApis from "../../../utilities/fitnessKits";
import { activityAPI } from "../../../utilities/apis";

const StepCard = (props) => {
  const fetchStepsFromFitnessKits = async () => {
    if (Platform.OS === "android") {
      await fitnessKitApis.historicSteps().then((res) => {
        setSteps(res);
      });
    } else {
      await fitnessKitApis.historicSteps((result) => setSteps(result));
    }
  };

  const [steps, setSteps] = useState(0);

  useEffect(() => {
    fetchStepsFromFitnessKits();
    const requestParams = { date: new Date(), steps };
    const { data, statusCode, error } = activityAPI.get(
      "/v1/user/steps/",
      requestParams,
    );
    // console.log(data, statusCode, error);
  }, [steps]);
  return (
    <CardXLarge>
      <Text>{steps}</Text>
    </CardXLarge>
  );
};

export default StepCard;

我知道我可以从组件传递authHeader,但这将导致在每个组件中添加2-3行代码,这不是超级方便。 谢谢

评论