Created
August 7, 2019 05:59
-
-
Save janicduplessis/5a53070755a5f79b603f28ec0c8f7dc5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Is this redux? | |
type ContactsState = { | |
loading: boolean; | |
error: Error | null; | |
data: Array<Contact>; | |
}; | |
function useContacts() { | |
const [contacts, setContacts] = React.useState<ContactsState>({ | |
loading: true, | |
error: null, | |
data: [], | |
}); | |
React.useEffect(() => { | |
const fetchContacts = async () => { | |
try { | |
let { status } = await Permissions.getAsync(Permissions.CONTACTS); | |
if (status !== Permissions.PermissionStatus.GRANTED) { | |
// TODO: Handle permissions denied. | |
await Permissions.askAsync(Permissions.CONTACTS); | |
} | |
const data = await getContactsAsync({ | |
fields: [EMAILS, PHONE_NUMBERS], | |
}); | |
setContacts(state => ({ | |
loading: false, | |
error: null, | |
data: state.data.concat(data.data), | |
})); | |
} catch (ex) { | |
setContacts({ | |
loading: false, | |
error: ex, | |
data: [], | |
}); | |
} | |
}; | |
fetchContacts(); | |
}, []); | |
return contacts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment