React-native-contacts: undefined is not an object

Created on 24 Sep 2017  Â·  25Comments  Â·  Source: morenoh149/react-native-contacts

Hi.
I've done npm install react-native-contacts and
react-native link react-native-contacts
Scanning 760 folders for symlinks in /home/alexander/projects/AwesomeProject/node_modules (11ms)

Here is my code:

import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { Font } from 'expo';
import Contacts from 'react-native-contacts';
export default class App extends React.Component {
  state = {
    fontLoaded: false
  };
  async componentDidMount() {
    await Font.loadAsync({
      'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
    });
    this.setState({ fontLoaded: true });
  };
  onPressExport() {
      // var Contacts = require('react-native-contacts');
      // var Contacts = require('./node_modules/react-native-contacts');
      if (window.Contacts || true) {
        if (Contacts.getAll || true) {
            Contacts.getAll((err, contacts) => {
                if (err === 'denied') {
                  // error
                  // error
                  // error
                  console.log('error');
                } else {
                  // contacts returned in []
                  console.log('ok');
                }
            });
        } else {
            console.log('Contacts.getAll == null');
        }
      } else {
          console.log('Contacts == null');
      }
  };
  render() {
    return (
      <View style={styles.container}>
        {
          this.state.fontLoaded ? (
            <Text style={{ fontFamily: 'open-sans-bold', fontSize: 22 }}>
              Привет, мир!
            </Text>
          ) : null
        }
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <Button
          onPress={this.onPressExport}
          title="Export"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
            />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  baseText: {
    fontFamily: 'open-sans-bold',
    fontSize: 20,
    fontWeight: 'bold'
  }
});

and error:

undefined is not an object (evaluating '_reactNativeContacts2.default.getAll')
onPressExport
    App.js:23:21
touchableHandlePress
    TouchableOpacity.js:129:45
_performSideEffectsForTransition
    Touchable.js:746:34
_receiveSignal
    Touchable.js:664:44
touchableHandleResponderRelease
    Touchable.js:433:24
invokeGuardedCallback
    ReactNativeStack-dev.js:130:19
invokeGuardedCallback
    ReactNativeStack-dev.js:166:43
invokeGuardedCallbackAndCatchFirstError
    ReactNativeStack-dev.js:169:64
executeDispatch
    ReactNativeStack-dev.js:202:128
executeDispatchesInOrder
    ReactNativeStack-dev.js:208:279
executeDispatchesAndRelease
    ReactNativeStack-dev.js:272:58
executeDispatchesAndReleaseTopLevel
    ReactNativeStack-dev.js:276:39
forEachAccumulated
    ReactNativeStack-dev.js:268:37
processEventQueue
    ReactNativeStack-dev.js:340:143
runEventQueueInBatch
    ReactNativeStack-dev.js:637:79
handleTopLevel
    ReactNativeStack-dev.js:642:29
<unknown>
    ReactNativeStack-dev.js:749:51
fiberBatchedUpdates
    ReactNativeStack-dev.js:691:14
performFiberBatchedUpdates
    ReactNativeStack-dev.js:695:31
perform
    ReactNativeStack-dev.js:1382:99
batchedUpdates
    ReactNativeStack-dev.js:2077:139
batchedUpdates$1
    ReactNativeStack-dev.js:1456:61
batchedUpdates
    ReactNativeStack-dev.js:699:31
batchedUpdatesWithControlledComponents
    ReactNativeStack-dev.js:708:30
_receiveRootNodeIDEvent
    ReactNativeStack-dev.js:748:46
receiveTouches
    ReactNativeStack-dev.js:762:60
__callFunction
    MessageQueue.js:266:47
<unknown>
    MessageQueue.js:103:26
__guard
    MessageQueue.js:231:6
callFunctionReturnFlushedQueue
    MessageQueue.js:102:17

Most helpful comment

Something problem in auto link. after manual link it works well.

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
  2. add ./node_modules/react-native-contacts/RCTContacts.xcodeproj
  3. In the XCode project navigator, select your project, select the Build Phases tab and in the Link Binary With Libraries section add libRCTContacts.a

All 25 comments

@apetrichkovich I think the problem with linking. Did you get the success messages after linking? Since this library is a pure native library. If native codes are not linked, It cannot export "Contacts". That's why you are getting "undefined is not an object" error.

I encountered this problem as well. In my case, i installed the react-native-contacts library as described by @apetrichkovich after the iOS simulator is already running. What I discovered is that react-native link react-native-contacts doesn't actually link the binary in the traditional sense where an executable is built (i.e ld.so ), but rather just specifies it as dependency that needs to be linked in the future . So doing a reload via "cmd+R" wont do anything as it only reloads the javascript file, instead of rebuilding the actual iOS app that'll contain the new native dependency.

So to remove the error, I simply had to quit iOS simulator and restart it again via react-native run-ios to actually re-build/link the executable. And now, the Contacts module becomes available instead of undefined.

Dont know wether this is up to date but today I stumbled upon the same problem. I installed the module via "yarn add" instead of npm... and forgot to link. After "react-native link react-native-contacts" and a rebuild via react-native run-ios everything works fine. @apetrichkovich: Maybe this can be closed?

Closing to minimize the number of outstanding issues. If you believe the installation instructions should be improved please submit a PR.

I'm still getting this problem even after linking, reinstalling..etc. Any ideas?

@sajsanghvi Can you show your code?

@wunderkind2k1

var Contacts = require('react-native-contacts')
Contacts.checkPermission( (err, permission) => {
});

Undefined is not an object "Contacts.checkPermission"

this definitely looks like a linking problem. Is your XCode up to date?

I am still having this problem but with Android. I've unlinked, uninstalled, reinstalled, relinked, verified it is linked ( Android module react-native-contacts is already linked).

I resolved this by adding some code in MainApplication.java

    protected List<ReactPackage> getPackage() {
        return Arrays.<ReactPackage>asList(
                new ReactNativeContacts()
        );
    }

Something problem in auto link. after manual link it works well.

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
  2. add ./node_modules/react-native-contacts/RCTContacts.xcodeproj
  3. In the XCode project navigator, select your project, select the Build Phases tab and in the Link Binary With Libraries section add libRCTContacts.a

@lyw0149 Thanks a bunch!!! That was extremely helpful. ios would not link for me with the react-native link command. The response was always successful, I restarted, re-built, everything, but the Contacts object remained undefined. Now it works great.

I'm using react-native-contacts: 2.1.1, and "react-native": 0.53.0

@lyw0149 Thanks Mate. You saved my time.

@morenoh149 Shouldn't we re-open this issue and fix the link problem?

@devhyunjae right, so the solution is to manually link?

@morenoh149 yup manual link fixed in my case

I'm still getting this error and I've tried the manual linking and react-native linking. I'm getting the same issue on both iOS and Android. The exact error is:

TypeError: undefined is not an object (evaluating '_reactNativeContacts2.default.getAll')

Below is my code:

import Contacts from 'react-native-contacts';
componentDidMount() {
    let contacts = Contacts.getAll((err, contacts) => {
        if (err === 'denied') {
          return console.log('denied contact book access');
        } else {
          return contacts;
        }
      });

Any idea if it's a bug or something with my code above?

Sorry, this might be too unique for what was happening to me to help - but maybe it can help you.

I've tried manually linking and auto-linking and nothing would work for me. The only library that worked for me linking to android and ios was react native navigation (wix). Every other library I needed for both would only successfully link to ios and always had undefined errors for android. I did two things to solve my problem: I made a new project (fresh init) reinstalling everything and made sure the way I linked react native navigation wasn't causing any trouble. Sadly I did both these at the same time and so I can't tell you if you could just do an init, or double check if another library is causing a problem.

But since doing that all the libraries for android (including this one) linked perfectly and worked, no errors. I lean towards my mismanagement of react native navigation fixing the problem more than the fresh init. If you aren't using a library that affects how android or ios deal with other packages then I would look elsewhere.

To clarify react native nav wasn't causing any problems, I had wrongly inputted how it should handle new libraries coming in (I think, again sadly I tried the init and fixing my implementation at the same time). Also to clarify - whenever I would check if linking was successful it always was, even if the library was undefined when ran. So you can only trust that it is trying to link the code, not that it is actually linked properly if you messed something else up like me.

Hi @HoogsterInc, thanks for this. Can you clarify what you mean by:

..and made sure the way I linked react native navigation wasn't causing any trouble.

I am also using react native navigation, and wondering if maybe I did something there that's messing with Contacts. Thanks!

I've got a terrible memory but let me try to remember what I had. So in step 5 of the docs for installing react native navigation, they say "add the following" so I had kept everything that was already in there and just added that below. But this is all they have in their example doc:
(for some reason my code snippets never stay inside the "insert code" shendig. sorry for any confusion below)

package com.example;

import android.support.annotation.Nullable;

import com.facebook.react.ReactPackage;
import com.reactnativenavigation.NavigationApplication;

import java.util.List;

public class MainApplication extends NavigationApplication {
    @Override
    public boolean isDebug() {
        return BuildConfig.DEBUG;
    }

    @Nullable
    @Override
    public List<ReactPackage> createAdditionalReactPackages() {
        return null;
    }

    @Nullable
    @Override
    public String getJSMainModuleName() {
        return "index";
    }
}

and that is it. Way less code than I had.

If I am remembering correctly I had two places where public List ... was happening. I made the assumption that this was causing confusion in the program of actually loading new packages in. So instead of "adding" that code in, they actually meant replace it (my opinion). Take this with a huge grain of salt because I am a noob, and once it was working I didn't delve any deeper. Also fyi I don't use the @Nullable in my code - if you look at the example step #5 again they have this:

protected List<ReactPackage> getPackages() {
         // Add additional packages you require here
         // No need to add RnnPackage and MainReactPackage
         return Arrays.<ReactPackage>asList(
             // eg. new VectorIconsPackage()
         );
     }

So unlike their example project where they return null, I have just the protected List that is returning the other packages. I use the code they have in the installation guide, not the example. I hope that helps!

Having the same issue on iOS.

I first linked via react-native link and it said it worked successfully.

Got the same TypeError: undefined is not an object (evaluating '_reactNativeContacts2.default.getAll') that @deepanjan1 is describing.

I tried manually linking on iOS following the instructions and still get the same result.

I'm on 2.2.1 and React Native 0.54.0.

Hi @catherinetcai, for me, because I was using Expo, I had to either use the Expo SDK Contacts API or eject my app. I decided to use the contacts API which works fine, but it can be slow on Android.

@deepanjan1 I'm not using Expo and I ran into the issue.

I actually resolved it doing this:

In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
add ./node_modules/react-native-contacts/RCTContacts.xcodeproj
In the XCode project navigator, select your project, select the Build Phases tab and in the Link Binary With Libraries section add libRCTContacts.a

closing as now we advise manually linking. If you are using pods and have an issue please open a new issue.

A simple

pod install

did the trick for me here for iOS.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gulshanzealous picture gulshanzealous  Â·  3Comments

uriva picture uriva  Â·  6Comments

caglardurmus picture caglardurmus  Â·  5Comments

msutyak picture msutyak  Â·  9Comments

dualcyclone picture dualcyclone  Â·  6Comments