0

Trying to get data on React Native native using axios method GET and local IP.

Running the URL on localhost using XAMPP works fine on the web.

But when trying to get data using api call on React Native, it's showing response.data as null on console.log()

Problem: the response.data on FreelancerScreen.js shows null. So, if anyone can help with this issue that would be great.

Code snippet provided below:

SignInScreen.js

    import React, { Component } from 'react';
import { StyleSheet, ScrollView, View, TextInput, } from 'react-native';
import { mapping, light as lightTheme, dark as darkTheme } from '@eva-design/eva';
import { ApplicationProvider, Layout, Text, Input, Button } from 'react-native-ui-kitten';

import Constants from '../constants/Constants';
import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';

export default class SignInScreen extends Component {
    static navigationOptions = {
        title: 'Sign In',
    };

    constructor(props) {
        super(props);
        this.state = {
            userName: 'freelancer',
            password: 'password',
        }
    }

    login() {
        console.log('Sign In Pressed');
        var self = this;
        axios({
            method: 'post',
            url: Constants.API_URL + 'auth/login/',
            data: {
                user_name: this.state.userName,
                password: this.state.password,
            },
            headers: {
                'X-API-KEY': 'xxxxx',
            },
        })
            .then(function (response) {
                if (response.data) {
                    AsyncStorage.setItem('my_token', response.data.token);
                    AsyncStorage.setItem('u_type', response.data.type);
                    //self.props.navigation.navigate('UserHome');
                    self.props.navigation.navigate('Freelancer');
                    console.log("Login Sucessful (response.data) ===> ", response.data);
                } else {
                    console.log('Login attempt Failed');
                }
            })
            .catch(function (error) {
                console.log(error)
                console.log('Error Response', error.response)
            });
    }

    render() {
        const { navigate } = this.props.navigation;

        return (
            <ApplicationProvider
                mapping={mapping}
                theme={lightTheme}>
                <Layout style={styles.container} level='1'>
                    <ScrollView>
                        <Text style={styles.text} category='h4'>Sign Up with Email</Text>
                        <TextInput label={'USERNAME'}
                            placeholder={'username'}
                            autoCapitalize='none'
                            style={styles.input}
                            onChangeText={userName => this.setState({ userName })}
                            value={this.state.userName} />

                        <TextInput label={'PASSWORD'}
                            placeholder={'Password'}
                            autoCapitalize='none'
                            style={styles.input}
                            onChangeText={password => this.setState({ password })}
                            value={this.state.password} />
                        <Button style={styles.button} onPress={() => this.login()}>SIGN IN</Button>
                    </ScrollView>
                </Layout>
            </ApplicationProvider>
        );
    }
}

const styles = StyleSheet.create({
    button: {
        marginTop: 15,
        marginLeft: 16,
        marginRight: 16
    },
    container: {
        flex: 1,
    },
    input: {
        marginLeft: 16,
        marginRight: 16,
        marginBottom: 15
    },
    text: {
        marginVertical: 16,
        textAlign: 'center'
    },
});

FreelancerScreen.js

import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import axios from 'axios';
import Constants from '../constants/Constants';
import AsyncStorage from '@react-native-community/async-storage';

export default class FreelancerScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],

            //-test
            totalBooked: null,
            dateStart: null,
        };
        console.log('Constructor()');
    }

    componentDidMount() {
        this.getAppointmentList();
        console.log('ComponentDidMount()')
    }

    getAppointmentList = () => {
        let self = this;
        AsyncStorage.getItem('my_token').then((keyValue) => {
            console.log('Freelancer Screen (keyValue): ', keyValue); //Display key value
            axios({
                method: 'get',
                url: Constants.API_URL + 'appointment_f/flist/',
                responseType: 'json',
                headers: {
                    'X-API-KEY': 'xxxxx',
                    //Authorization: `Bearer ${keyValue}`,
                    Authorization: keyValue,
                },
            })
                .then(function (response) {
                    console.log('response.data: ===> ', response.data)
                    console.log('Response: ', response);
                    self.setState({
                        dataSource: response.data,
                    })
                })
                .catch(function (error) {
                    console.log('Error Response: ', error.response);
                });
        }, (error) => {
            console.log('error error!', error) //Display error
        });
    }

    clearAsyncStorage = async () => {
        await AsyncStorage.clear();
        this.props.navigation.navigate('SignIn');
        console.log('Logged Out.')
    }

    render() {
        const { dataSource } = this.state;
        return (
            <View>
                <Text style={{ marginLeft: 20 }}> FreelancerScreen </Text>
                <TouchableOpacity onPress={() => this.clearAsyncStorage()}>
                    <Text style={{ margin: 20, fontSize: 25, fontWeight: 'bold' }}>LogOut</Text>
                </TouchableOpacity>
                {<FlatList
                    data={dataSource}
                    renderItem={({ item }) => {
                        return (
                            <View>
                                <Text style={{ marginLeft: 20 }}>date_start: {item.date_start}</Text>
                                <Text style={{ marginLeft: 20 }}>total_booked: {item.total_booked}</Text>
                            </View>
                        );
                    }}
                />}
            </View>
        );
    }
};



/*data: {
    total_booked: this.state.totalBooked,
    date_start: this.state.dateStart,
},*/

Screenshot (React-native): console screenshot

Screenshot (web Localhost): Headers Headers 2 Preview Response

Update: I log_message the backend code and got errors such as Trying to get property of non-object and undefined index

Community
  • 1
  • 1
Beep Boop
  • 327
  • 6
  • 30
  • What does the _Network_ tab show? – Phil Dec 09 '19 at 03:14
  • Do you think you have configured backend CORS properly? Are the code for axios API request the same on web and mobile? – Loi Nguyen Huynh Dec 09 '19 at 03:52
  • @phil here you go [screenshot 1](https://prnt.sc/q6ijv4) [screenshot 2](https://prnt.sc/q6ilg6) [screenshot 3](https://prnt.sc/q6imb4) [screenshot 4](https://prnt.sc/q6imph) – Beep Boop Dec 09 '19 at 04:03
  • @HuỳnhLợiNguyễn regarding the backend, I am not sure as it's not done by me but I do have the code. And yes, the code for axios API request is somewhat similar for web and mobile. – Beep Boop Dec 09 '19 at 04:06
  • **Update:** I log_message the backend and got errors such as _Trying to get property of non-object_ and _undefined index_ – Beep Boop Dec 09 '19 at 04:09
  • 1
    And the web platform can still access the API using the same code? It smells like the CORS error (which could be configured in the backend) due to the difference of endpoints between your mobile and web server development. Try communicating with the backend guy if there's something he can do. – Loi Nguyen Huynh Dec 09 '19 at 04:13
  • 1
    may be it is your server error, https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined – Prashanth Reddy Dec 09 '19 at 05:10
  • @HuỳnhLợiNguyễn yes the web API can access it. I think it's the server error as well. Thank you. – Beep Boop Dec 09 '19 at 05:47
  • @PrashanthReddyBalemula I think server error as well. Thank you for the stackoverflow post. – Beep Boop Dec 09 '19 at 05:48

0 Answers0