2

I'm very new to API, and recently I started learning React Native and found some quick tutorial about RN frontend and Laravel backend just App just to show how is API working between. So I done everything step by step but my data from laravel, server is not fetching... Here is my whole code

Starting from Laravel first This is my CoinController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Coin;

class CoinController extends Controller
{
    public function index()
    {
        $coins = Coin::all();

        return response()->json($coins);
    }
}

Here is my migration for coin table:

class CreateCoinsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('coins', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('coins');
    }
}

Here is my api.php file:

Route::get('coins', 'CoinController@index');

And here is my env file:

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:sqFYSTaGklMTMtSFjRWQjKbIfhPWiGFq1p3JzJOdfOg=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=routingproj
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

And now React Native app Here is my App.js

// App.js

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import Coin from './src/screens/Coin';

const AppNavigator = createStackNavigator({
  CoinScreen: {screen: Coin},
});

export default createAppContainer(AppNavigator);

My Coin.js

// Coin.js

import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import ajax from '../services/FetchCoins';
import CoinList from '../components/CoinList';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#B6A6BB',
  },
});

export class Coin extends Component {
  state = {
    coins: [],
  };

  async componentDidMount() {
    const coins = await ajax.FetchCoins();
    this.setState({coins});
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.coins.length > 0 ? (
          <CoinList coins={this.state.coins} />
        ) : (
          <Text>No coins</Text>
        )}
      </View>
    );
  }
}

export default Coin;

Here is my FetchCoin.js

// FetchCoins.js

const URI = 'http://my_ip_address/routingproj/public/api/coins';

export default {
  async fetchCoins() {
    try {
      let response = await fetch(URI + '/api/coins');
      let responseJsonData = await response.json();
      return responseJsonData;
    } catch (e) {
      console.log(e);
    }
  },
};

And my CoinList.js

// CoinList.js

import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';

export default class CoinList extends Component {
  static propTypes = {
    coins: PropTypes.array.isRequired,
  };
  render() {
    return (
      <View style={styles.coinsList}>
        {this.props.coins.map(coin => {
          return (
            <View key={coin.id}>
              <Text style={styles.cointext}>
                {coin.name} | {coin.price}
              </Text>
            </View>
          );
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  coinsList: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-around',
  },
  cointext: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

That is all of my code and when i run react-native run-android it shows me No Coins, so that mean my data from server doesn't fetch. Any solutions?

2
  • 1
    Sidenote: You posted the same block of code for CoinController and your migration. Commented Sep 13, 2019 at 14:17
  • 1
    Sorry, my mistake I edited it! Thank you! Commented Sep 13, 2019 at 21:01

1 Answer 1

4

Please check your laravel response from browser or Postman, if it's okey, please check fetchCoin.js file becouse as I understand it your API endpoint is repeated.

Your URI value is finished with /api/coins but at the bottom line you used as fetch(URI + 'api/coins' )

so it's mean /api/coins + /api/coins

as a result you are trying to fetch data from an incorrect URL;

http://my_ip_address/routingproj/public/api/coins/api/coins

// FetchCoins.js

const URI = 'http://my_ip_address/routingproj/public/api/coins';

export default {
  async fetchCoins() {
    try {
      let response = await fetch(URI + '/api/coins');
      let responseJsonData = await response.json();
      return responseJsonData;
    } catch (e) {
      console.log(e);
    }
  },
};
Sign up to request clarification or add additional context in comments.

5 Comments

I'm doing it right now, sorry for my late respond Sir !
So i changed it like this const URI = 'http://my_ip_address/routingproj/public and on my fetch I leave everything same so (URI + '/api/coins'); but nothing happend... On my android emulator it still shows me No Coins. I checked my laravel response from browser and it's okay, when I route my browser to localhost/routingproj/public/api/coins it shows me all my data from server. Sir is there any more solutions?
It's also shows me this warning: Possible Unhandled Promise Rejection (id:0): Type Error:_FetchCoins.default.FetchCoins is not a function. (In '_FetchCoins.default.FetchCoins()', '_FetchCoins.default.FetchCoins is undefined)
Okay for this warning I fix my mistake, it was async fetchCoins() it has to be async FetchCoins(). But it still shows me No Coins
Okay so now it shows me just No Coins without any warnings, but after some time, maybe 20 seconds it throws me this: TypeError: undefined is not an object (evaluating 'this.state.coins.length') This error is located at: in Coin (at SceneView.js:9). What is this ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.