I created an api with laravel and now i want to be able to consume it using React-native but it's not working at all and I have no clue about it. Here are some code that i think can be helpful to help you try to help me.
That's my api.js file.
import {create} from 'apisauce';
import { AsyncStorage } from 'react-native';
const api = create({
baseURL:'http://127.0.0.1:8000/api',
});
api.addAsyncRequestTransform( request => async () => {
const token = await AsyncStorage.getItem('#PetFinder:token');
if(token) {
request.headers['Authorization'] = `Bearer ${token}`;
}
request.headers['Content-Type'] = `application/json`;
request.headers['accept'] = `application/json`
});
And here is my Login page
import React from 'react';
import { View, Button } from 'react-native';
import api from '../../services/api'
export default function Login() {
async function handleSubmit()
{
const response = await api.post('/login', {
email: 'nowahmst#gmail.com',
password:'123456',
});
}
return (
<View><Button onPress={handleSubmit} title="Login" > </Button></View>
);
}
Back-End is running, I'm able to get the response using postman or insomnia and my route is set to be post as well the api request.
Related
I am adding Facebook login to my expo app and it says in the documentation to enter my expoClientId somewhere.
The problem is I cant figure out where to put it. Do I put it in my app.json? Maybe my package.json? In the Facebook developer portal somewhere? Maybe I put it in my expo console somewhere?
Does anyone know where the expoClientId should live? The documentation doesn't say where to put it.
Edit: It looks like I also need to place an iosClientId and an androidClientId as well.
It seems it's a part of the FacebookAuthRequestConfig interface which is used as useAuthRequest() parameter (Expo src).
Turns out you pass it in the request to authorize with facebook like this:
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Facebook from 'expo-auth-session/providers/facebook';
import { ResponseType } from 'expo-auth-session';
import { initializeApp } from 'firebase/app';
import { getAuth, FacebookAuthProvider, signInWithCredential } from 'firebase/auth';
import { Button } from 'react-native';
// Initialize Firebase
initializeApp({
/* Config */
});
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [request, response, promptAsync] = Facebook.useAuthRequest({
responseType: ResponseType.Token,
clientId: <YOUR FBID>,
expoClientId: <YOUR FBID>, //this is where you add them
iosClientId: <YOUR FBID>,
androidClientId: <YOUR FBID>,
});
React.useEffect(() => {
if (response?.type === 'success') {
const { access_token } = response.params;
const auth = getAuth();
const credential = FacebookAuthProvider.credential(access_token);
// Sign in with the credential from the Facebook user.
signInWithCredential(auth, credential);
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();}}
/>
);
}
I had started a project a little while ago and have been busy lately so I have not been able to work on it. I am out of practice with web development because I had recently joined the military. Right now the project consists of a create-react-app app with auth0 integrated. What I am trying to do is get the plaid link integrated into the page it takes you after logging in using auth0. I am requesting help on what code from the plaid docs I use in order for this to work. Their documentation is a little confusing to me, maybe because I'm so out of practice. Any help would be much much appreciated.
https://github.com/CollinChiz/SeeMyCash
Have you taken a look at the Quickstart at https://github.com/plaid/quickstart/? It contains a full React implementation that does this. Here's the relevant excerpt:
// APP COMPONENT
// Upon rendering of App component, make a request to create and
// obtain a link token to be used in the Link component
import React, { useEffect, useState } from 'react';
import { usePlaidLink } from 'react-plaid-link';
const App = () => {
const [linkToken, setLinkToken] = useState(null);
const generateToken = async () => {
const response = await fetch('/api/create_link_token', {
method: 'POST',
});
const data = await response.json();
setLinkToken(data.link_token);
};
useEffect(() => {
generateToken();
}, []);
return linkToken != null ? <Link linkToken={linkToken} /> : <></>;
};
// LINK COMPONENT
// Use Plaid Link and pass link token and onSuccess function
// in configuration to initialize Plaid Link
interface LinkProps {
linkToken: string | null;
}
const Link: React.FC<LinkProps> = (props: LinkProps) => {
const onSuccess = React.useCallback((public_token, metadata) => {
// send public_token to server
const response = fetch('/api/set_access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ public_token }),
});
// Handle response ...
}, []);
const config: Parameters<typeof usePlaidLink>[0] = {
token: props.linkToken!,
onSuccess,
};
const { open, ready } = usePlaidLink(config);
return (
<button onClick={() => open()} disabled={!ready}>
Link account
</button>
);
};
export default App;
I have an existing app in expo create in react-native. In that app I have to add expo push notification functionality. I have created the NotificationController using below link:
https://docs.expo.io/versions/v32.0.0/guides/push-notifications
I now need to know where I have to place this controller. I am very new in mobile development and just need help about the correct placement of this controller so that we can show this to the customer.
Once you have created your push notification service , either this can be a function in a single file in side your services directory (create if it doesn't exists) , or a component.
Then import that function inside your main app.js and use it inside componentDidMount lifecycle function. This is just a sample code and I'm sure this can be improved further, However this is enough to get started.
push_notification.js
import {Permissions, Notifications} from 'expo';
import { ActivityIndicator, AsyncStorage} from 'react-native';
export default async () => {
try{
let previousToken = await AsyncStorage.getItem('pushToken');
if(previousToken){
return;
}else{
let {status} = await Permissions.askAsync(Permissions.NOTIFICATIONS);
console.log(status);
if(status !== 'granted'){
console.log("Don't like to receive push");
}
let token = await Notifications.getExpoPushTokenAsync();
return token;
}
} catch(err){
console.log(err);
}
};
App.js
import PushNotification from "../services/push_notifications";
import axios from 'axios';
async componentDidMount(){
let tokenFromStorage = await zlAsyncStorage.getItem('pushToken');
console.log('token from storage',tokenFromStorage);return;
let token = await PushNotification();
AsyncStorage.setItem('pushToken',token);
console.log("here");
//Save the token in couch db
await axios({
url:"http://192.168.8.148:5984/mycompany",
method: 'post',
timeout: 1000,
headers: {
'Accept-Encoding' : 'gzip, deflate',
'Content-Type':'application/json',
'Authorization':'Basic YTph'
},
data: {
user: "cheran",
tokenReceived : token,
},
auth: {
username: 'a',
password: 'a'
},
}).then(function(response){
//console.log(response);
});
}
I have a problem with my reducer. I am using redux to create a login page. I have successfully logged in yet I failed to navigate to the next page. The state in my reducer is not updated. How do I solve this?
This is how I wrote my reducer:
import { LOGIN_SUCCESS } from '../actions/types';
const INITIAL_STATE={
isLoginSuccess:false,
}
export default function (state=INITIAL_STATE, action){
switch(action.type){
case LOGIN_SUCCESS:
return {
isLoginSuccess : true
}
default:
return INITIAL_STATE;
}
}
This is how I wrote my action:
import axios from 'axios';
import * as helper from '../common';
import { LOGIN_SUCCESS } from './types';
export const attemptLogin = (username, password) => async dispatch => {
let param = {
txtNomatrik: username,
txtPwd: password,
public_key: helper.PUBLIC_KEY,
secret_key: helper.SECRET_KEY
}
console.log(`${helper.ROOT_API_URL}/v1/basic/ad/std/login`)
let login_res = await
axios.post(`${helper.ROOT_API_URL}/v1/basic/ad/std/login`, param)
console.log(login_res.data);
if (login_res.data.status == 'Successful Login') {
const { login } = login_res.data;
await AsyncStorage.seItem('Login_token', username);
await AsyncStorage.setItem('profile', JSON.stringify(login));
dispatch({ type: LOGIN_SUCCESS, payload: { isLoginSuccess : true } });
}
}
I want to use the isLoginSuccess in my index file to navigate login to the next page like this:
componentWillReceiveProps(nextProps){
if(nextProps.isLoginSuccess){
this.props.navigation.navigate('logged');
}
}
Below is how I connect redux:
const mapStateToProps = ({ auth }) => {
return {
isLoginSuccess: auth.isLoginSuccess
}
}
export default connect(mapStateToProps, actions)(LoginScreen);
Below is my combineReducer file:
import {combineReducers} from 'redux';
import news from './welcome_reducer';
import auth from './login_reducer';
export default combineReducers({
news,
auth
})
How do I solve this? I feel lost now, have tried a lot of ways to solve it . The Api call for login is successful but the action is not dispatched at all. I can't update the state and I can't navigate to the next page. Please help me
I am using react-native 0.49.3 version, My Question is how to get the device token in react native for both IOS and Android I tried with this link but it not working for me, right now I tried in IOS. how to resolve it can one tell me how to configure?
I tried different solutions and I've decided to use React Native Firebase.
Here you will find everything about Notifications.
Also, you can use the others libraries that come with Firebase, like Analytics and Crash Reporting
After set up the library you can do something like:
// utils/firebase.js
import RNFirebase from 'react-native-firebase';
const configurationOptions = {
debug: true,
promptOnMissingPlayServices: true
}
const firebase = RNFirebase.initializeApp(configurationOptions)
export default firebase
// App.js
import React, { Component } from 'react';
import { Platform, View, AsyncStorage } from 'react-native';
// I am using Device info
import DeviceInfo from 'react-native-device-info';
import firebase from './utils/firebase';
class App extends Component {
componentDidMount = () => {
var language = DeviceInfo.getDeviceLocale();
firebase.messaging().getToken().then((token) => {
this._onChangeToken(token, language)
});
firebase.messaging().onTokenRefresh((token) => {
this._onChangeToken(token, language)
});
}
_onChangeToken = (token, language) => {
var data = {
'device_token': token,
'device_type': Platform.OS,
'device_language': language
};
this._loadDeviceInfo(data).done();
}
_loadDeviceInfo = async (deviceData) => {
// load the data in 'local storage'.
// this value will be used by login and register components.
var value = JSON.stringify(deviceData);
try {
await AsyncStorage.setItem(config.DEVICE_STORAGE_KEY, value);
} catch (error) {
console.log(error);
}
};
render() {
...
}
}
Then you can call the server with the token and all the info that you need.