Marco Disco
Marco Disco

Reputation: 565

How to call a variable with data in React Native

Sometghing really basic but I didn't understant. Once I get the contacts how can I use them to populate the Flatlist? I always get Can't find variable: contacts

import * as Contacts from "expo-contacts";

const ContactsScreen = props => {
  useEffect(() => {
    (async () => {
      const { status } = await Contacts.requestPermissionsAsync();
      if (status === "granted") {
        const { data } = await Contacts.getContactsAsync({
          fields: [Contacts.Fields.Emails]
        });

        if (data.length > 0) {
          const contact = data[0];
          console.log(contact);
        }
      }
    })();
  }, []);


  return (
    <View >
      <Text>Contacts Module</Text>
      <FlatList
        data={contact}
        keyExtractor={contact.id}
        renderItem={({ item }) => (
      <ContactItem
        firstName={item.firstName}
      />
    </View>
  );
};

export default ContactsScreen;

I think it's really simple, I just don't understand

Upvotes: 0

Views: 45

Answers (2)

yesIamFaded
yesIamFaded

Reputation: 2068

Answer from my comment:

I think that might be because of the scope of the variable , it could be that RN doenst know it exists because it only lives inside the function. I guess you could set up a State and then assign the values from contact to the state and in ur flatlist call data ={ this.state.contact}.

or by using hooks like you do :

if (data.length > 0) {
          setContact(data);
        }

and call it in flatlist:

data={myContact} // if named so in state declaration

Upvotes: 1

aytek
aytek

Reputation: 1942

You need to keep your contacts in the component's state. So every time you change your state, your component will render itself and you will see the updated data. Change your code with the following. Don't forget to import useState.

import * as Contacts from "expo-contacts";

const ContactsScreen = props => {
  const [myContacts, setMyContacts] = useState([]);

  useEffect(() => {
    (async () => {
      const { status } = await Contacts.requestPermissionsAsync();
      if (status === "granted") {
        const { data } = await Contacts.getContactsAsync({
          fields: [Contacts.Fields.Emails]
        });

        if (data.length > 0) {
          setMyContacts(data);
        }
      }
    })();
  }, []);


  return (
    <View >
      <Text>Contacts Module</Text>
      <FlatList
        data={myContacts}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <Text>{item.firstName}</Text>
        )}
      />
    </View>
  );
};

export default ContactsScreen;

Upvotes: 1

Related Questions