почтовый запрос не работает в реактивно-натуре - PullRequest
0 голосов
/ 15 июня 2019

Я пытаюсь вызвать поддельный API аутентификации, используя axios, когда я вызываю действие, которое делает сетевой запрос. Мой поток действий

  1. отправка логинЗапрос
  2. сделать запрос API
  3. в случае успешной отправки логинУспешно
  4. при сбое отправки loginFaliure

Сначала он вызывает действие loginRequest, затем не вызывает никаких действий, даже loginFaliure но если я проверяю вкладку сети, запрос успешен если я сделаю запрос get, все действия будут отправлены, как они должны

Я попытался получить, затем с помощью Axios

App.js

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import reducers from './src/store/reducers';
import LoginPage from './src/components/pages/Login';
// import './src/config/ReactotronConfig';
// import Reactotron from 'reactotron-react-native';

// To see all the requests in the chrome Dev tools in the network tab.
XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest;

// fetch logger
global._fetch = fetch;
global.fetch = function(uri, options, ...args) {
    return global._fetch(uri, options, ...args).then(response => {
        console.log('Fetch', { request: { uri, options, ...args }, response });
        return response;
    });
};

// redux integration
const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

const store = createStore(reducers, applyMiddleware(...middleware));

export default class App extends Component {
    render() {
        // Reactotron.log('hello from AppContainer');

        return (
            <Provider store={store}>
                <LoginPage />
            </Provider>
        );
    }
}

1025 * редукторы *

import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_REQUEST } from '../constants/auth';
import { AsyncStorage } from 'react-native';

// _retrieveData = async () => {
//  try {
//      const value = await AsyncStorage.getItem('token');
//      if (value !== null) {
//          // We have data!!
//          return value;
//      }
//      return null;
//  } catch (error) {
//      // Error retrieving data
//      console.log('error fetching token', error);
//  }
// };

// const isuser =  _retrieveData();

const isuser = null;

const innitialState = {
    token: isuser ? isuser : null,
    userName: isuser ? 'ketan kulkarni' : null,
    isAuthenticated: isuser ? true : false,
    isAuthenticating: false,
    statusText: isuser ? 'Logged In' : null,
};

export const auth = (state = innitialState, action) => {
    switch (action.type) {
        case LOGIN_REQUEST:
            return { ...state, isAuthenticating: true };
        case LOGIN_SUCCESS:
            return {
                ...state,
                token: action.token,
                userName: action.userName,
                isAuthenticating: false,
                isAuthenticated: true,
                statusText: 'You have been successfully logged in',
            };
        case LOGIN_FAILURE:
            return {
                ...state,
                token: null,
                userName: null,
                isAuthenticated: false,
                isAuthenticating: false,
                statusText: `Authentication Error ${action.status} ${action.statusText}`,
            };
        case LOGOUT_REQUEST:
            return {
                ...state,
                isAuthenticated: false,
                token: null,
                userName: null,
                statusText: 'You have been successfully logged out.',
            };
        default:
            return state;
    }
};

действия

import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOGOUT_REQUEST } from '../constants/auth';
import axios from 'axios';

export const loginRequest = () => ({
    type: LOGIN_REQUEST,
});

export const loginSuccess = title => {
    return {
        type: LOGIN_SUCCESS,
        token: title,
        username: 'ketan',
    };
};

export const loginFailure = error => {
    return {
        type: LOGIN_FAILURE,
        status: 'error.response.status',
        statusText: 'login failed',
    };
};

export const logout = () => {
    return { type: LOGOUT_REQUEST };
};

export const loginUser = (email, password) => async dispatch => {
    dispatch(loginRequest());
    try {
        console.log('requesting');
        const res = await axios.get(`https://reqres.in/api/login`, { email, password });
        console.log('request done', res);
        //decode token then
        dispatch(loginSuccess('data'));
    } catch (error) {
        console.log({ error });
        dispatch(loginFailure(error));
    }
    // setTimeout(() => {
    //  if (1) dispatch(loginSuccess('data'));
    // }, 2000);

    // axios
    //  .post(`https://reqres.in/api/login`, { email, password })
    //  .then(() => dispatch(loginSuccess('data')))
    //  .catch(err => dispatch(loginFailure(err)));

    // fetch('https://reqres.in/api/login', {
    //     method: 'GET',
    //     headers: {
    //         Accept: 'application/json',
    //         'Content-Type': 'application/json',
    //     },
    //     body: JSON.stringify({
    //         email,
    //         password,
    //     }),
    // })
    //     .then(() => dispatch(loginSuccess('data')))
    //     .catch(err => dispatch(loginFailure(err)));
};

LoginPage

import React, { Component } from 'react';
import { Button, StyleSheet, View } from 'react-native';
import { loginUser } from '../../store/actions/auth';
import { connect } from 'react-redux';

class LoginPage extends Component {
    _onPressButton = async () => {
        await this.props.dispatch(loginUser('eve.holt@reqres.in', 'cityslicka'));
        console.log('here');
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.buttonContainer}>
                    <Button onPress={this._onPressButton} title="Press Me" />
                </View>
            </View>
        );
    }
}

export default connect(null)(LoginPage);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
    },
    buttonContainer: {
        margin: 20,
    },
    alternativeLayoutButtonContainer: {
        margin: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
});

Ожидаемый результат -

первый дипатч loginRequest если запрос API успешен, отправление loginSuccessful если запрос API не удается отправить диспетчер loginFailure

Фактическая выработка -

при отправке запроса отправить логинRequest тогда никакое действие не получает отправку

если получен запрос на получение все работает правильно

1 Ответ

0 голосов
/ 15 июня 2019

код, который я добавил в App.js для проверки сетевого запроса на вкладке сети, вызывал ошибку

// To see all the requests in the chrome Dev tools in the network tab.
// XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest;

// // fetch logger
// global._fetch = fetch;
// global.fetch = function(uri, options, ...args) {
//  return global._fetch(uri, options, ...args).then(response => {
//      console.log('Fetch', { request: { uri, options, ...args }, response });
//      return response;
//  });
// };
...