Facebook Login using Exponent React Native - react-native

Need help guys, currently using exponent and accessing the Exponent.Facebook.logInWithReadPermissionsAsync for authentication. Anyone has a guide in setting up the project. I can't find the iOS folder since in the instruction of facebook sdk, I need to add few libraries on the project. Here's my main.js:
import Expo from 'expo';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Button } from 'react-native-elements';
class App extends React.Component {
authenticate = (token) => {
const provider = firebase.auth.FacebookAuthProvider;
const credential = provider.credential(token);
return firebase.auth().signInWithCredential(credential);
}
login = async () => {
const ADD_ID = 273131576444313
const options = {
permissions: ['public_profile', 'email'],
}
const {type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(ADD_ID, options)
if (type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`)
console.log(await response.json());
this.authenticate(token);
}
}
render() {
return (
<View style={styles.container}>
<Text>Open up main.js to start working on your app!</Text>
<Button
raised
onPress={this.login}
icon={{name: 'cached'}}
title='RAISED WITH ICON' />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Expo.registerRootComponent(App);
`

Try putting single quotes around the APP_ID

Related

Errors with reactNative/voice in expo

thats my code
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, Button, View } from 'react-native';
import { useEffect, useState } from 'react';
import Voice from '#react-native-voice/voice';
export default function App() {
let [started, setStarted] = useState(false);
let [results, setResults] = useState([]);
useEffect(() => {
Voice.onSpeechError = onSpeechError;
Voice.onSpeechResults = onSpeechResults;
return () => {
Voice.destroy().then(Voice.removeAllListeners);
}
}, []);
const startSpeechToText = async () => {
await Voice.start();
setStarted(true);
};
const stopSpeechToText = async () => {
await Voice.stop();
setStarted(false);
};
const onSpeechResults = (result) => {
setResults(result.value);
};
const onSpeechError = (error) => {
console.log(error);
};
return (
<View style={styles.container}>
{!started ? <Button title='Start Speech to Text' onPress={startSpeechToText} /> : undefined}
{started ? <Button title='Stop Speech to Text' onPress={stopSpeechToText} /> : undefined}
{results.map((result, index) => <Text key={index}>{result}</Text>)}
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
when I run it I keep getting this error
[Unhandled promise rejection: TypeError: null is not an object (evaluating 'Voice.startSpeech')]
I tried asking chatGPT but he can't answer it
Packages and import is correct, so I don't know what the error is nor how I can fix it
Check if it works on another version of android, I launched some emulators and it seems that below Android 12 there are problems with Permissions.
On Android 12 and above, my code with react-native-voice works well with expo run:android but I can't find out why once built with expo build:android I still have problems with mic permissions

Amplify Tutorial (Expo) and got error message on signin

I'm doing this tutorial: https://docs.amplify.aws/start/getting-started/auth/q/integration/react-native#create-login-ui
I followed it completely and did everything they told me to do. The Todo works, but when I added Auth, and wrapped it. The project will start. Users can create accounts. But when you try to sign in on iOS it won't work. Strangely, when I tested it on web, users could sign in. Leading me to think it is a problem with iOS. I tested it on my iPhone with expo installed and it failed there too.
Here is a link to my issue: https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508
This is my app.js
import config from './aws-exports'
Amplify.configure(config)
import { withAuthenticator } from 'aws-amplify-react-native'
import React, { useEffect, useState } from 'react'
import {
View, Text, StyleSheet, TextInput, Button
} from 'react-native'
import { API, graphqlOperation } from 'aws-amplify'
import { createTodo } from './graphql/mutations'
import { listTodos } from './graphql/queries'
const initialState = { name: '', description: '' }
const App = () => {
const [formState, setFormState] = useState(initialState)
const [todos, setTodos] = useState([])
useEffect(() => {
fetchTodos()
}, [])
function setInput(key, value) {
setFormState({ ...formState, [key]: value })
}
async function fetchTodos() {
try {
const todoData = await API.graphql(graphqlOperation(listTodos))
const todos = todoData.data.listTodos.items
setTodos(todos)
} catch (err) { console.log('error fetching todos') }
}
async function addTodo() {
try {
const todo = { ...formState }
setTodos([...todos, todo])
setFormState(initialState)
await API.graphql(graphqlOperation(createTodo, {input: todo}))
} catch (err) {
console.log('error creating todo:', err)
}
}
return (
<View style={styles.container}>
<TextInput
onChangeText={val => setInput('name', val)}
style={styles.input}
value={formState.name}
placeholder="Name"
/>
<TextInput
onChangeText={val => setInput('description', val)}
style={styles.input}
value={formState.description}
placeholder="Description"
/>
<Button title="Create Todo" onPress={addTodo} />
{
todos.map((todo, index) => (
<View key={todo.id ? todo.id : index} style={styles.todo}>
<Text style={styles.todoName}>{todo.name}</Text>
<Text>{todo.description}</Text>
</View>
))
}
</View>
)
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
todo: { marginBottom: 15 },
input: { height: 50, backgroundColor: '#ddd', marginBottom: 10, padding: 8 },
todoName: { fontSize: 18 }
})
export default withAuthenticator(App)```
I feel like the problem might be with the ./aws-exports potentially. There was a bug where you had to move it out of src, etc. Anyone have any ideas?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/1Wt6J.png
I found out that the login error was due to a bug with expo deprecating a file. See this issue for more. https://github.com/aws-amplify/amplify-js/issues/8113#issuecomment-830995508

How to prompt camera permission when a button is clicked in react?

SOLVED!: Check the one reply below. It solves it. But, after you allow camera, when you click the button again, it won't prompt again, which is natural. You have to deny camera from the emulator or phone's settings again for it to prompt again.
I am basically trying to do this: a button, when clicked; it will prompt the user of camera permission, in react. In my current app here, it asks on first launch of the app. I tried various ways to implement it with button, but to no avail. But this code works, without error. Here is my app.js:
import React, {Component} from 'react'
import {StyleSheet, View, Text, Button} from 'react-native'
import {Permission, PERMISSION_TYPE} from 'D:/Reactdeneme/reacttest/src/AppPermission'
export default class App extends Component {
componentDidMount() {
Permission.checkPermission(PERMISSION_TYPE.camera)
//this the thing that prompts the camera permission. I want this in a button.
}
render() {
return (
<View style={styles.container}>
<Text style={{fontSize: 30}}>izinler</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
THIS PART IS PROBABLY OPTIONAL, so please don't be afraid of the long code blocks. Here is my AppPermissions.js aswell:
import {check, request, PERMISSIONS, RESULTS} from 'react-native-permissions';
import {Platform} from 'react-native'
const PLATFORM_CAMERA_PERMISSIONS= {
ios:PERMISSIONS.IOS.MICROPHONE,
android: PERMISSIONS.ANDROID.CAMERA
}
const REQUEST_PERMISSION_TYPE = {
camera: PLATFORM_CAMERA_PERMISSIONS
}
const PERMISSION_TYPE= {
camera: 'camera'
}
class AppPermission {
checkPermission= async (type): Promise<boolean> => {
console.log("AppPermission checkPermission type:", type)
const permissions = REQUEST_PERMISSION_TYPE[type][Platform.OS]
console.log("AppPermission checkPermission permissions:", permissions)
if(!permissions){
return true
}
try {
const result = await check(permissions)
console.log("AppPermission checkPermission result:", result)
if (result === RESULTS.GRANTED) return true
return this.requestPermission(permissions)
} catch (error) {
console.log("AppPermission checkPermission error:", error)
return false
}
}
requestPermission=async(permissions): Promise<boolean> => {
console.log("AppPermission requestPermission permissions:", permissions)
try {
const result = await request(permissions)
console.log("AppPermission requestPermission result:", result)
return result === RESULTS.GRANTED
}catch(error) {
console.log("AppPermission requestPermission error:", error)
return false
}
}
}
const Permission = new AppPermission()
export {Permission, PERMISSION_TYPE}
You should read more react-native docs.
Remove checkPermission in componentDidMount and add this to onPress props of Button.
import React, {Component} from 'react'
import {StyleSheet, View, Text, Button} from 'react-native'
import {Permission, PERMISSION_TYPE} from 'D:/Reactdeneme/reacttest/src/AppPermission'
export default class App extends Component {
checkPermission = () => {
Permission.checkPermission(PERMISSION_TYPE.camera);
}
render() {
return (
<View style={styles.container}>
<Text style={{fontSize: 30}}>izinler</Text>
<Button title="Check" onPress={this.checkPermission}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})

react native navigation Could not find "store" in either the context or props of "Connect(facebookLogin)

I'm building react native app authentication with facebook login.
I'm using stack navigator and I want to add redux to my app.
I just seperate my files to components and when I use stack navigation with redux I get this error
Could not find "store" in either the context or props of
"Connect(facebookLogin)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(facebookLogin)".
index.android.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity, AppRegistry, Image } from 'react-native';
import facebookLogin from './src/components/FacebookLogin';
import Home from './src/components/Home';
import {
StackNavigator,
} from 'react-navigation';
const App = StackNavigator({
Home: { screen: facebookLogin },
HomePage: {screen:Home},
})
AppRegistry.registerComponent('facebookLogin', () => App);
FacebookLogin.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity, AppRegistry, Image } from 'react-native';
import FBSDK, { LoginManager, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import Icon from 'react-native-vector-icons/FontAwesome';
// redux
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../reducers/ProfileReducers';
const store = createStore(reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
class facebookLogin extends Component {
constructor(props) {
super(props);
this.state = {
result: null
}
}
_fbAuth() {
const { navigate } = this.props.navigation;
LoginManager.logInWithReadPermissions(['public_profile','user_birthday']).then((result) => {
if (result.isCancelled) {
console.log('Login was canclled');
}
else {
console.log(result);
const infoRequest = new GraphRequest(
'/me?fields=id,name,picture.width(800).height(800),gender,birthday,first_name,last_name',
null,
(error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
console.log(result);
this.setState({ result });
navigate('HomePage');
}
}
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start();
}
}, function (error) {
console.log('An error occured:' + error);
})
}
getProfileData() {
const { ImageStyle } = styles;
if (this.state.result) {
return (
<View>
{this.state.result.picture ? <Image style={ImageStyle} source={{ uri: this.state.result.picture.data.url }}></Image> : null}
<Text> first name: {this.state.result.first_name} </Text>
<Text> Last name: {this.state.result.last_name} </Text>
<Text> Gender {this.state.result.gender} </Text>
</View>
)
}
return null;
}
render() {
return (
<Provider store = {store}>
<View style={styles.container}>
<Icon.Button name="facebook" backgroundColor="#3b5998" onPress={() => { this._fbAuth() }}>
<Text style={{fontFamily: 'Arial', fontSize: 15, color:'white'}}>Login with Facebook</Text>
</Icon.Button>
{this.getProfileData()}
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
ImageStyle:{
borderRadius:80,
width:100,
height:100
}
});
const mapStateToProps = (state) => {
return
{ profile: state.profile};
}
export default connect(mapStateToProps)(facebookLogin);
when it was only one component in index.android.js it works fine without any error but when I seperate it to some components using stack navigation I get this error.
my profileReducers
var profile = {
name :'',
email:'',
photo:''
}
const initialState = {
profile,
};
export default (state = initialState, action) => {
console.log("state");
switch (action.type) {
case 'INSERT_PROFILE_DETAILS':
return {
profile: action.payload
}
case 'GET_PROFILE_DETAILS': {
return state;
}
default:
return state;
}
}
Try setting up redux in index.android.js instead so it looks something like this:
// Set up redux store above
const Navigator = StackNavigator({
Home: { screen: facebookLogin },
HomePage: { screen: Home },
});
const App = () => (
<Provider store={store}>
<Navigator />
</Provider>
);
AppRegistry.registerComponent('facebookLogin', () => App);

React Native Facebook Login using official fbsdk

I tried following the starter tutorial by setting up a new React Native Project for iOS. But the loginbutton doesn't seem to be working. Any help is appreciated.
Here's the index.ios.js:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
const FBSDK = require('react-native-fbsdk');
const {
LoginButton
} = FBSDK;
var Login = React.createClass({
render: function() {
return (
<View>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
alert("login has finished with permissions: " + result.grantedPermissions)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
});
class AwesomeProject extends Component {
render() {
return (
<View style={styles.container}>
<Text>
Login to Facebook
</Text>
<Login />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
shareText: {
fontSize: 20,
margin: 10,
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
And the screenshot of the emulator:
You need to link the sdk's iOS project in your app's project.
If you're using react-native-sdk v0.2.0+, rnpm will take care of this step and you can follow the tips here to complete set up.
If you're using the older version, you need to link react-native-fbsdkxxx.xcodeproj in YourApp.xcodeproj. Follow the manual linking steps in https://facebook.github.io/react-native/docs/linking-libraries-ios.html