繁体   English   中英

如何进行依赖于另一个调用设置的值的 API 调用?

[英]How can I make an API call that depends on a value which is set by another call?

我有一个登录功能,我在其中设置了一个令牌,该令牌保存在 redux 存储中,然后,在登录发生后,我需要再次调用 api,该 api 将为主屏幕提供数据。 但是为了打那个电话,我需要令牌。

这是我需要进行调用的主屏幕组件:

// imports

import styles from '../../styles/HomeScreenStyles';
import { passengersDataAction } from './actions/homeScreen';

class HomeScreen extends Component {
  static navigationOptions = {
    header: null,
  };

  componentDidMount() {
    this.GetPassengersData();
  }

  GetPassengersData = async () => {
    // userToken is coming from the store
    const { passengersDataActionHandler, userToken } = this.props;
    if (userToken && userToken !== null) {
      try {
        const response = await fetch(
          'http://myAPI/public/api/getPassengers',
          {
            method: 'POST',
            headers: {
              Authorization: `Bearer ${userToken}`,
              Accept: 'application/json',
              'Content-Type': 'application/json',
            },
          },
        );
        const responseJson = await response.json();
          passengersDataActionHandler(responseJson.success.data);      
      } // catch ...
    }
  };

  render() {
    return <TabView style={styles.container} />;
  }
}

// export

GetPassengersData被调用时, userToken还不存在,所以我的请求直接转到 catch 错误回调。

我该如何处理?

编辑:我上面的 API 调用是我需要令牌的地方。

调用以获取登录数据:

import { Alert, AsyncStorage } from 'react-native';
import { has } from 'lodash';
import PropTypes from 'prop-types';

const FetchLoginData = async (
  username,
  password,
  navigation,
  userTokenActionHandler,
) => {
  try {
    const response = await fetch(
      'http://myAPI/public/api/driverlogin',
      {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: username, password }),
      },
    );
    const responseJson = await response.json();
    if (has(responseJson, 'error')) {
      Alert.alert('Error', 'Please check your credentials.');
    } else {
      // HERE I SET THE TOKEN
      await AsyncStorage.setItem('userToken', responseJson.success.token);
      userTokenActionHandler(responseJson.success.token);
      navigation.navigate('App');
    }
  } catch (error) {
    Alert.alert(
      'Error',
      'There was an error with your request, please try again later.',
    );
  }
};

FetchLoginData.propTypes = {
  navigation: PropTypes.shape({}).isRequired,
  userTokenActionHandler: PropTypes.func.isRequired,
};

export default FetchLoginData;

您可以在此处拨打第二个电话:

try {
    const response = await fetch(
      'http://myAPI/public/api/getPassengers',
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${userToken}`,
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      },
    );
   const responseJson = await response.json();
      passengersDataActionHandler(responseJson.success.data);  

   // **put second call here you have token here send it to second api call**

  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM