how to debug network responce in react native - android

i am trying to debug my code in react native here i have a axios post request the only responce is i get when there is a error is axios error
rather than that i am looking to debug my code just like in react js by inspect element and network tab
currently i open my app using npx react-native run-andoid this opens the app in a emulator and is really diffcult to debug my code can anyone suggest a better method for debugiing
var Data56 = {
name: name,
email: email,
babyname: babyname,
phone: nuber,
baby_date: date,
};
}
axios
.post('http://10.0.2.2:8000/api/register', Data56, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(res => {
props.navigation.navigate('Home_scrren', {data: Data56});
})
.catch(error => {
alert(error);
});
}

Follow this Step:-
(1) First you need to shake the device and open the debug option, it will redirect you to chrome.
(2) You need to inspect that and open the console tab.
(3) You need to add breakpoints in VSCode or add breakpoints using chrome.
(4) then simply Reload the application, using that you can do step-by-step debugging.

if (__DEV__) {
global.XMLHttpRequest = global.originalXMLHttpRequest
? global.originalXMLHttpRequest
: global.XMLHttpRequest;
global.FormData = global.originalFormData
? global.originalFormData
: global.FormData;
fetch; // Ensure to get the lazy property
if (window.__FETCH_SUPPORT__) {
// it's RNDebugger only to have
window.__FETCH_SUPPORT__.blob = false;
} else {
/*
* Set __FETCH_SUPPORT__ to false is just work for `fetch`.
* If you're using another way you can just use the native Blob and remove the `else` statement
*/
global.Blob = global.originalBlob ? global.originalBlob : global.Blob;
global.FileReader = global.originalFileReader
? global.originalFileReader
: global.FileReader;
}
}
add this code to root index.js
turn on debug
Check tab network like web,
we can see request and response,
one more option, you can add reactotron or flipper, this tool will log anything like network redux action..., without open debug mode
Hope this help you

1]firstly you can see this video
2]exapmle with axios
3] 2nd go to your console window and press D and see your emulator like this like this
if you press d in console window and see your output in your emulator
like this then then on the last option "Debug"
it will navigate to chrome screen here is screenshot
then write click on a screen and see option like inspect here is
screenshot
then then new screen will appear and go to consol tab there you can
see your data like this
I This this will help you

I'm using axios and fetch data and you can see in chrome i will get all data in debug mood also I'm my step which one I post here
import React, { useEffect, useState } from "react";
import { View, SafeAreaView, Text, StyleSheet, ScrollView, TouchableOpacity, FlatList } from "react-native";
import axios from "axios";
const App = () => {
const [list, setList] = useState([]);
useEffect(() => {
getList()
}, [])
const getList = () => {
axios({
url: "https://fakestoreapi.com/users?limit=5",
}).then((res) => {
var response = res.data;
console.log(response)
setList(response)
})
}
return (
<FlatList
data={list}
renderItem={({ item }) =>
<Text>{item}</Text>
}
/>
)
}
export default App;

Related

I wanted to know if anyone has an agreement with how PostHog.setup works in react native

PostHog.setup issue only occurs in android studio with xcode. The error it produces is "apiKey must not be null or empty ".
In ios it works perfectly which seems strange to me, i'm not sure what i'm doing wrong
the function is used as follows
import Posthog from 'posthog-react-native';
import Gleap from 'react-native-gleapsdk'
export default function App() {
useAutoUpdateAppHandler({
versionUrl: config.versionUrl,
versionRelease: config.versionRelease,
appName: 'UPchieve',
});
Posthog.setup(posthogConfig.token, posthogConfig.settings)
Gleap.initialize(gleapConfig.token)
}
this is the config
const Config = {
demo: {
webSocketUrl: 'https:...',
socketUrl: 'wss://demo....',
baseUrl: 'https://demo....',
versionUrl: 'https://cdn....',
versionRelease: '2.0.0',
},
prod: {
baseUrl: 'https://...',
},
posthog: {
token: '',
settings: {
host: 'https://...',
captureApplicationLifecycleEvents: true,
captureDeepLinks: true,
iOS: {
capturePushNotifications: true,
}
}
},
}
If your posthog.token is the empty string in the actual config that could be causing the error
In the documentation you can see that the token should be the "Project API key" from the settings page of your PostHog project. https://app.posthog.com/project/settings if you're on PostHog cloud

FeathersJS login error when building for Android

I am building an Android app using Ionic. And using the following feathers_client.js
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const auth = require('#feathersjs/authentication-client');
const io = require('socket.io-client');
const socket = io('http://mydomain.example:3030');
const feathers_client = feathers();
feathers_client
.configure(socketio(socket))
.configure(auth({ storage: window.localStorage }));
module.exports = feathers_client;
When I run the app at the browser it works fine. But when I run it at an Android device I only get "NotAuthenticated".
I am assuming this is happening because FeathersJS stores the JWT token at window.localStorage and this is not available at the Android app userspace.
Two questions:
1) Is there any way to tell FeathersJS to store this token somewhere else?
2) If not, anyone faced this situation and may provide me a solution?
By the way, this is my code for authenticating:
export class SSHSettingsPage implements OnInit {
public inputEmail: string;
public inputPassword: string;
constructor() { }
ngOnInit() {
}
public performLogin($event) {
let authObj: object = { "strategy": "local", "email": this.inputEmail, "password": this.inputPassword};
client.authenticate(authObj)
.then(res => {
console.log(res);
window.localStorage.setItem("user",JSON.stringify(res.user));
window.location.href = "/download";
})
.catch(err => {
console.log(err);
window.location.href = "/login-error";
})
}
}
As mentioned in the configuration API the storage option can be passed an instance of the React Native AsyncStorage:
import {AsyncStorage} from 'react-native';
// Available options are listed in the "Options" section
app.configure(auth({
storage: AsyncStorage
}))

React Navigation without navigation prop does not work in release mode (Android signed app)

I am implementing a react-native app that receives firebase push notification. When a notification arrives the app navigate to a screen to show the notification.
I followed this approach using reference:
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
When I tested this with debug mode, it works perfectly. But when I tested in release mode (android signed app) it does not work.
Especially, when the notification arrives when the app is open, it does not work. There is no error message and the app become freezing and in a 30 seconds or so, the app crashes.
Here are package info:
"react": "16.8.3",
"react-i18next": "10.12.2",
"react-native": "0.59.10",
"react-native-firebase": "5.5.6",
"react-native-gesture-handler": "1.3.0",
"react-navigation": "3.11.1",
Basically, I tried this
"Navigating without the navigation prop"
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
Similarly, this one too:
https://github.com/react-navigation/react-navigation/issues/742
I am using not class component but functional component.
// Navigator.js
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
loginFlow: createStackNavigator({
Signin: SigninScreen,
Signup: SignupScreen
}),
helpFlow: createStackNavigator({
Help: HelpScreen,
}, {headerLayoutPreset: 'center'}),
mainFlow: createBottomTabNavigator({
Ask: createStackNavigator({
AskMain: AskScreen,
AskWait: AskWaitScreen,
}, {headerLayoutPreset: 'center'}),
Chat: createStackNavigator({
ChatList: ChatListScreen,
Chatting: ChatScreen,
}, {headerLayoutPreset: 'center'}),
Profile: createStackNavigator({
Account: AccountScreen,
AccountEdit: AccountEditScreen,
ProfileContract: ProfileScreen
}
, {headerLayoutPreset: 'center'})
},
...
export default createAppContainer(switchNavigator);
// App.js
import Navigator from './Navigator';
import { useTranslation } from 'react-i18next';
import { navigate, setNavigator } from './src/navigationRef';
const App = Navigator;
export default () => {
// setup language
const { t } = useTranslation();
// use effect
useEffect(() => {
// notification listener (triggered when a particular notification has been received)
// if the app is foreground, we need to navigate the screen
const listenerFG = firebase.notifications().onNotification((notification: Notification) => {
console.log('onNotification', notification);
Alert.alert(
t('AppScreen.title'),
t('AppScreen.message'),
[
{text: t('yes'), onPress: () => navigate('Help', { notificationBody: notification })},
],
{cancelable: true},
);
});
listenerForAppClosed();
return () => {
listenerFG();
}
}, []);
return (
<App ref={(navigator) => { setNavigator(navigator) }} />
);
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
In debug mode, using `navigate('any screen') works like a charm, but in release mode, it does not work.
But one strange thing is that the following navigation works. A user opens a push notification when the app is not foreground state.
// part of App.js
// listen the notification being opened or clicked when the app is closed
const listenerForAppClosed = async() => {
// app closed
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
// app was opened by a notification
console.log('getInitialNotification', notificationOpen);
// get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
//// ignore the same notification id since the same notification is received again, don't know why.
// get noti id from storage
const notiId = await AsyncStorage.getItem('notiId');
// set noti id to storage
await AsyncStorage.setItem('notiId', notification.notificationId);
if (notification.notificationId === notiId) {
console.log('notification id is the same');
} else {
console.log('navigating to helpscreen...');
// navigate to Help screen
navigate('Help', { notificationBody: notification });
}
}
}
The problem happens both on Android emulator and a device (Android9).
Why the navigate('Help') does not work in release mode? I searched many documents and I feel that it should work in release mode too.
Is there any other way to navigate to a screen from top-level (like App.js)?
I found the source of the problem.
I tested several things.
I wanted to know that whether very simple app in release mode navigates properly.
So, I just followed this posting:
https://medium.com/#katharinep/firebase-notification-integration-in-react-native-0-60-3a8d6c8d56ff
Here are what I did:
- created two screens: Home and Notification.
- Re-created the app with latest react-native#0.60.6 and react-navigation#4.0.9
- sent cloud message not from the app but from the firebase cloud messaging
It worked! When a notificaiton arrives the app navigated to the notification screen.
So I tried to track down the source of the problem.
- tried to add more screens
- added more providers and context
- sent message from the app
Finally, I found the source. It was how I used 'navigateRef.js'
Originally I used it like this:
// App.js
import { navigate, setNavigator } from './src/navigationRef';
<App ref={(navigator) => { setNavigator(navigator) }} />
// navigationRef.js
import { NavigationActions } from 'react-navigation';
let navigator;
// nav is coming from react navigation
export const setNavigator = navRef => {
console.log('navigation ref', navRef);
// set navigator
navigator = navRef;
};
export const navigate = (routeName, params) => {
console.log('[navigate dispatch] navigator', navigator);
navigator.dispatch(
NavigationActions.navigate({
routeName,
params
})
);
};
I simply used the exact the code from react-navigation:
https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
// App.js
import NavigationService from './src/NavigationService';
<App
ref={navigationRef =>
{NavigationService.setTopLevelNavigator(navigationRef);}}
/>
// NavigationService.js
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
}
Then I worked! I do not know the difference of these two codes.
The first one worked perfectly in debug mode but not in release mode, especially the app is in foreground.
Could anyone tell me the difference? Why the first code does not work?

Share images and files on react-native using Expo

I've saved the file i want to share locally using FileSystem.downloadAsync
Share.share works fine for iOS. How can I share an image I have saved locally on Android?
I've tried
https://github.com/lucasferreira/react-native-send-intent
https://github.com/react-native-community/react-native-share
Both these solutions do not seem to work with Expo.
I'm using react-native version : https://github.com/expo/react-native/archive/sdk-31.0.0.tar.gz
FileSystem.downloadAsync(url, FileSystem.documentDirectory+filename).then(({uri})=>{
if(Platform.OS == "android"){
// ???
}
else{
Share.share({url:uri});
}
})
Is there something i'm missing?
Since SDK33, you can use Expo Sharing to share any type of file to other apps that can handle its file type even if you're on Android.
See : https://docs.expo.io/versions/latest/sdk/sharing/
Usage is pretty simple :
import * as Sharing from 'expo-sharing'; // Import the library
Sharing.shareAsync(url) // And share your file !
In order for users to share content saved within our (Expo) app, we structured it like this. (This is working across iOS & Android).
IMPORT SHARING:
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
ADD ONPRESS TO BUTTON (OR WHEREVER):
<Button
name="share"
onPress={() =>
openShareDialogAsync(media, {
video: media.meta.fileType === 'video',
})
}
/>
SHARE VIDEO OR IMAGE TO ANY APP IN USERS HANDSET
const openShareDialogAsync = async (mediaProp, options) => {
const fileDetails = {
extension: options.video ? '.mp4' : '.jpg',
shareOptions: {
mimeType: options.video ? 'video/mp4' : 'image/jpeg',
dialosTitle: options.video
? 'Check out this video!'
: 'Check out this image!',
UTI: options.video ? 'video/mp4' : 'image/jpeg',
},
};
const downloadPath = `${FileSystem.cacheDirectory}${mediaProp.media_id}${fileDetails.extension}`;
const { uri: localUrl } = await FileSystem.downloadAsync(
mediaProp.url,
downloadPath
);
if (!(await Sharing.isAvailableAsync())) {
showMessage({
message: 'Sharing is not available',
description: 'Your device does not allow sharing',
type: 'danger',
});
return;
}
await Sharing.shareAsync(localUrl, fileDetails.shareOptions);
};
Hope this helps :]

IONIC 2 send message to multiple recipients

So developing this IONIC 2 app, I discoverd that sending SMS to multiple recipients isnt so trivial at it should be.
After a long research I've found this post where people trys to deal with multiple SMS. But even using their specs it doesnt work properly.
They say we can use an array of strings representing multiple phone numbers. So far so good, except it works only for the first number.
If someone has now details on this functionality I would love to hear about it.
Thanks
import { SMS } from '#ionic-native/sms';
constructor( private sms: SMS ){
this.sendSMS();
}
sendSMS() {
var MultiNumber = [ '1234567890' , '9876543210' ];
this.sms.send(MultiNumber, 'hello all this is testing message');
}
try this it is working for me, Hope it is working for you too.
So after ages of research over internet I got this litle jam called cordova-plugin-sms ( dont confuse it with cordova-sms-plugin ).
As it says in their documentation they have a function sendSMS which reeeally sends messages to multiple recipients.
So my solution for integrating it in IONIC 2 is as follows :
ionic cordova plugin add cordova-plugin-sms
and my Ionic 2 class is :
import { Component } from '#angular/core';
import { NavController, ToastController } from 'ionic-angular';
import { Http, Response } from "#angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
declare let window: any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(private toastCtrl: ToastController, public navCtrl: NavController, public http: Http ) { }
ionViewDidLoad() {
this.startWhatchSMS();
}
// Android ONLY
startWhatchSMS() {
if (window.SMS) {
window.SMS.startWatch(() => {
//console.log("startWatch");
}, error => {
//console.log(error);
//console.log("error startWatch");
});
}
document.addEventListener('onSMSArrive', this.smsArived);
}
// Android ONLY
smsArived = (result: any) => {
//console.log(result);
let sms = result.data;
// put your code here...
}
sendTextMessage( ) {
window.SMS.sendSMS([ '1234567890' , '0987654321' ], 'Text message for multiple recipients',
(result) => {
console.log(result); // should be 'OK' string
}, (error) => {
console.log(error);
});
}
}
The sendTextMessage() function is called from the template by clicking an button.
Well thats it ... for me is working and hope will work for you too.
Cheers

Categories

Resources