App won't connect to backend

The backend works fine but the app fails to load response data.
Code from ListingScreen.js:

const [ listings, setListings ] = useState([]);
  const [ error, setError ] = useState( false );

  useEffect( () => {
    loadListings();
  }, [] );

  const loadListings = async () => {
    const response = await listingsApi.getListings();
    if ( !response.ok ) return setError( true );

    setError( false );
    setListings( response.data );
  };

Hey.
I just wanted to know if you didn’t not use localhost when setting your assetsBaseUrl

I used my IP like mosh told us to do, followed every step and rechecked everything I think. Even tried both IP4 and IP6.

1 Like

You probably need to debug the code inside your listingsApi.getListings(). Knowing the error will help us know more about the issue.

My debug dosent really work as it should. Port 19001 yields nothing. I get some response from 19000, but all I can gather is that listings “Failed to load response data”. But I already knew that. Because I can load the listings in my browser, althoug it looks different from the video.

Can you post the code that is inside getListings() .
I assume it has a line like this below:

if (res.status === 200)

Before this line you need to add this and show us the output console.log(res);

development.json

{
  "assetsBaseUrl": "http://[ ip address ]/assets/",
  "port": 9000
}

My api/listings.js

import client from './client';

const endpoint = '/listings';   // Also tried './listings'

const getListings = () => client.get( endpoint );

export default {
  getListings,
};

My api/client.js

import { create } from 'apisauce';

const apiClient = create({
  baseURL: 'http://[ ip address ]/api',
});

export default apiClient;

My ListingsScreen.jsx

import React, { useEffect, useState } from 'react';
import { ... } from 'react-native';

{ ... }   // Various imports
import listingsApi from '../api/listings';
import routes from '../navigation/routes';

function ListingsScreen({ navigation }) {
  const [ listings, setListings ] = useState([]);
  const [ error, setError ] = useState( false );

  useEffect( () => {
    loadListings();
  }, [] );

  const loadListings = async () => {
    const response = await listingsApi.getListings();
    if ( !response.ok ) return setError( true );

    setError( false );
    setListings( response.data );
  };

  return (
    <Screen style={ styles.screen }>
      {
        error && <React.Fragment>
          <AppText>Couldn't retrive the listings.</AppText>
          <AppButton title='Retry' onPress={ loadListings } />
        </React.Fragment>
      }
      <FlatList
        data={ listings }
        keyExtractor={ listing => listing.id.toString() }
        renderItem={ ({item}) => (
          <Card
            title={ item.title }
            subTitle={ '$'+item.price }
            imageUrl={ item.images[0].url }
            onPress={ () => navigation.navigate( routes.LISTING_DETAILS, item )}
          />
        )}
      />
    </Screen>
  );
}

const styles = StyleSheet.create({ ... });

export default ListingsScreen;

Your code I don’t recognize from the course.

Replace the code below:

if ( !response.ok ) return setError( true );

With:

if ( !response.ok ) {
    console.log(response);
    return setError( true );
} 

Now in your console you will see the actual error which is failing the API call.

`This is the only error in the console. The only thing I can gather from this is that I can’t connect to the backend or the backend returns undefined

TypeError: Cannot read property 'toString' of undefined

This error is located at:
    in VirtualizedList (at FlatList.js:624)
    in FlatList (at ListingsScreen.jsx:44)
    in RCTView (at View.js:34)
    in View (at Screen.jsx:12)
    in RCTSafeAreaView (at SafeAreaView.js:51)
    in ForwardRef(SafeAreaView) (at Screen.jsx:11)
    in Screen (at ListingsScreen.jsx:37)
    in ListingsScreen (at SceneView.tsx:122)
    in StaticContainer
    in StaticContainer (at SceneView.tsx:115)
    in EnsureSingleNavigator (at SceneView.tsx:114)
    in SceneView (at useDescriptors.tsx:153)
    in RCTView (at View.js:34)
    in View (at CardContainer.tsx:245)
    in RCTView (at View.js:34)
    in View (at CardContainer.tsx:244)
    in RCTView (at View.js:34)
    in View (at CardSheet.tsx:33)
    in ForwardRef(CardSheet) (at Card.tsx:573)
    in RCTView (at View.js:34)
    in View (at createAnimatedComponent.js:165)
    in AnimatedComponent (at createAnimatedComponent.js:215)
    in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:555)
    in PanGestureHandler (at GestureHandlerNative.tsx:13)
    in PanGestureHandler (at Card.tsx:549)
    in RCTView (at View.js:34)
    in View (at createAnimatedComponent.js:165)
    in AnimatedComponent (at createAnimatedComponent.js:215)
    in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:544)
    in RCTView (at View.js:34)
    in View (at Card.tsx:538)
    in Card (at CardContainer.tsx:206)
    in CardContainer (at CardStack.tsx:623)
    in RCTView (at View.js:34)
    in View (at Screens.tsx:84)
    in MaybeScreen (at CardStack.tsx:616)
    in RCTView (at View.js:34)
    in View (at Screens.tsx:54)
    in MaybeScreenContainer (at CardStack.tsx:498)
    in CardStack (at StackView.tsx:462)
    in KeyboardManager (at StackView.tsx:458)
    in SafeAreaProviderCompat (at StackView.tsx:455)
    in RCTView (at View.js:34)
    in View (at StackView.tsx:454)
    in StackView (at createStackNavigator.tsx:87)
    in StackNavigator (at FeedNavigator.jsx:11)
    in FeedNavigator (at SceneView.tsx:122)
    in StaticContainer
    in StaticContainer (at SceneView.tsx:115)
    in EnsureSingleNavigator (at SceneView.tsx:114)
    in SceneView (at useDescriptors.tsx:153)
    in RCTView (at View.js:34)
    in View (at BottomTabView.tsx:55)
    in SceneContent (at BottomTabView.tsx:172)
    in RCTView (at View.js:34)
    in View (at ResourceSavingScene.tsx:68)
    in RCTView (at View.js:34)
    in View (at ResourceSavingScene.tsx:63)
    in ResourceSavingScene (at BottomTabView.tsx:166)
    in RCTView (at View.js:34)
    in View (at src/index.native.js:123)
    in ScreenContainer (at BottomTabView.tsx:146)
    in RNCSafeAreaProvider (at SafeAreaContext.tsx:74)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:42)
    in SafeAreaProviderCompat (at BottomTabView.tsx:145)
    in BottomTabView (at createBottomTabNavigator.tsx:45)
    in BottomTabNavigator (at AppNavigator.jsx:14)
    in AppNavigator (at App.js:14)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:409)
    in ForwardRef(BaseNavigationContainer) (at NavigationContainer.tsx:91)
    in ThemeProvider (at NavigationContainer.tsx:90)
    in ForwardRef(NavigationContainer) (at App.js:13)
    in App (created by ExpoRoot)
    in ExpoRoot (at renderApplication.js:45)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:106)
    in DevAppContainer (at AppContainer.js:121)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:132)
    in AppContainer (at renderApplication.js:39)
at node_modules\expo\build\logs\LogSerialization.js:160:14 in _captureConsoleStackTrace
at node_modules\expo\build\logs\LogSerialization.js:41:26 in serializeLogDataAsync
- ... 9 more stack frames from framework internals

[Unhandled promise rejection: TypeError: Cannot read property 'toString' of undefined]
at app\screens\ListingsScreen.jsx:46:30 in FlatList.props.keyExtractor
at node_modules\react-native\Libraries\Lists\FlatList.js:519:13 in _keyExtractor
at node_modules\react-native\Libraries\Lists\VirtualizedList.js:894:18 in _pushCells
- ... 8 more stack frames from framework internals

It looks like you have a variable at line 44 of ListingsScreen.jsx on which you’re calling toString, while its value is undefined.

If this doesn’t help, can you upload your code somewhere (preferably github)? To make the upload quick, just make sure you aren’t committing or uploading the node_modules folder.

Actually I haven’t bought this specific course but I am an experienced React/React Native developer and could help you I have access to the code.

Line 44 works exactly as intended. Where the problem is is that getListings fetches an undefined variable instead of the json object from the backend Mosh provided. Every line is identical to the one in the course. this I’m sure of becuase I’ve tripple checked twice. I can upload my code somewhere if you really need me to. But every relevant piece of code I’ve already provided. Except from the backend which Mosh created. I’m honestly at a loss for what to do.

Edit: The previous error has just been magicaly resolved and the response have been logged in the console.

{duration: 2134, problem: "NETWORK_ERROR", originalError: Error: Network Error
    at createError (http://[ ip address ]:19000/node_modules%5Cexpo%5CAppEntry.…, ok: false, status: null, …}
config:
  adapter: Ć’ xhrAdapter(config)
  baseURL: "http://[ ip address ]/api"
  data: undefined
  headers: {Accept: "application/json"}
  maxBodyLength: -1
  maxContentLength: -1
  method: "get"
  params: {}
  timeout: 0
  transformRequest: [Ć’]
  transformResponse: [Ć’]
  transitional: {silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false}
  url: "/listings"
  validateStatus: Ć’ validateStatus(status)
  xsrfCookieName: "XSRF-TOKEN"
  xsrfHeaderName: "X-XSRF-TOKEN"
  __proto__: Object
data: null
duration: 2134
headers: null
ok: false
originalError: Error: Network Error at createError (http://[ ip address ]:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:168819:17) at XMLHttpRequest.handleError (http://[ ip address ]:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:168729:16)
problem: "NETWORK_ERROR"
status: null
__proto__: Object

response.problem returns NETWORK_ERROR

Have you tried putting your actual ip address in the code?

In case putting you local ip address doesn’t work (which is in a form of 192.168.x.y, where x and y are numbers), try putting the ip address you get from https://whatismyipaddress.com/

If it doesn’t work either, you can upload the source code at Github (public repo) and share the link of the repo here. I will take a look at it.

[ ip address ] is just a placeholder to hide my ip. I’ve tried localhost, IP4 and IP6 numerous times. I’ve fetched my IP4 from your link and from my computers settings. When I used the address provided by whatismyipaddress.com I got the toString error and localhost, IP6 and the IP4 provided by settings>network>wifi just returned the NETWORK_ERROR string.

It seems to me that the later is the most telling error because it is an error documented by apisauce so the question is what it exactly means and how to fix a network errror.

Do you need the backend aswell or only the code I’ve written?

Upload both the frontend and backend source code please.

Was this resolved? I’m having the same issue.

well we need to activate the backend but the problem comes when we run the server it returns a
no module found-express here is what it came for me

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- C:\Users\iftkh\app\Backend\index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Users\iftkh\app\Backend\index.js:1:17)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\\Users\\iftkh\\app\\Backend\\index.js' ]
}

I think you need to run npm install from your server’s folder before starting itYour server should now run.

(post deleted by author)

(post deleted by author)

I’m sorry for late answer. Exams and christmas and shit you know.

Backend and app folder, app.js and app.json. The whole projct with packages would take too much space.

1 Like