Я не могу понять, почему это не работает.Я думаю, что это связано с тем, что обещание вложено в другое обещание:
Я настроил свой объект службы API:
api.js
import axios from 'axios';
import apiConfig from './apiConfig';
import deviceStorage from '../services/deviceStorage.js';
export const get = (endpoint, payload = {}, headers = {}) => {
const jwt = deviceStorage.loadJWT
headers.Authorization = jwt
console.log("running..");
axios({
method: 'GET',
url: apiConfig.development.url + endpoint,
headers: headers,
data: payload,
}).then((response) => {
console.log('will return response..');
return response;
}).catch((error) => {
console.log('will return error..');
return error;
});
};
, затем я вызываю его с экрана:
NotificationsScreen.js
import React from 'react';
import { View, ScrollView, Text, Button, StyleSheet } from 'react-native';
import axios from 'axios';
import Header from '../components/Header';
import NotificationCardSection from '../components/notificationsScreen/NotificationCardSection';
import NotificationCardList from '../components/notificationsScreen/NotificationCardList';
import { Loading } from '../components/common/';
import globalStyles from '../globalStyles';
import * as api from '../services/api'
export default class NotificationsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
notifications: [],
error: ''
};
}
componentDidMount() {
console.log("will get data from api");
api.get(
'/notifications'
).then((response) => {
console.log("got back data from api");
this.setState({
notifications: response.data.data,
loading: false
});
}).catch((error) => {
console.log("got error from api");
this.setState({
error: 'Error retrieving data',
loading: false
});
});
}
но я получаю ошибку:
TypeError: Cannot read property 'then' of undefined.
терминал показывает 'running..'
, но не показывает 'will return response...'
или 'will return error'
, поэтому они не запускаются.
Я предполагаю, что это потому, что вызов API еще не завершен, но, поскольку он асинхронный, как я могу убедиться, что он завершился при вызове с экрана?