Can't find variable: document - android

I'm trying to install data grid to my mobile app and i always go step by step in documentation of each library. I installed everyting and it writes me error message
I Tried to google, look to the files of library, but nothing. Noone hasn't have this type of problem as I have :/.
import React from 'react';
import ReactDataGrid from 'react-data-grid';
const columns = [
{ key: 'id', name: 'ID' },
{ key: 'title', name: 'Title' },
{ key: 'count', name: 'Count' } ];
const rows = [{id: 0, title: 'row1', count: 20}, {id: 1, title: 'row1', count: 40}, {id: 2, title: 'row1', count: 60}];
function HelloWorld() {
return (<ReactDataGrid
columns={columns}
rowGetter={i => rows[i]}
rowsCount={3}
minHeight={150} />);
}
I did everyting, what is written here:
https://github.com/adazzle/react-data-grid
https://adazzle.github.io/react-data-grid/docs/quick-start
Is there any way to repair it ? I can send you anything, but i really need it. Thanks a lot for help :)

This library is intended for web applications that run in the browser. When running in the context of a browser, the document element is available by default.
In React Native, however, the set of elements is different, and this kind of library is probably not going to work.
As an alternative, you can use something like React Native Paper that has a data table component. There are quite a few libraries that offer this kind of functionality for React Native.

First and foremost React != React Native
This should help you to dig around and will of course help to why the document is not available.
What you need to understand first is the difference between a Web Application and a mobile application.

Related

How do you get the value from a JavaScript function in Flutter WebView?

Hi I have a webView and I'm simply trying to get the value from the WebView to return true or false when the user presses a button, I have managed to console.log it, but how do I get this value and put it into flutter? Thanks.
web.WebView(
initialUrl: "https://www.tiktok.com/#tiktok",
javascriptMode: web.JavascriptMode.unrestricted,
onWebViewCreated: (web.WebViewController webViewController) {
_controller.complete(webViewController);
_myController = webViewController;
},
onPageFinished: (String url) {
_myController.evaluateJavascript("""
window.onclick = e => {
console.log(e.target.className);
console.log(e.target.tagName);
}
var element = document.getElementsByClassName('jsx-4074580611');
element[0].addEventListener('click', function(event) {
setTimeout(function (){
if(element[0].innerText == 'Following') {
console.log("True");
//RETURN TRUE TO FLUTTER
}else{
console.log("False");
//RETURN FALSE TO FLUTTER
}
}, 1500);
});
""");
},
javascriptChannels: Set.from([
])
),
);
}
}
You won't get anything back from the webpage like this, because the page doesn't know how to talk back to your Flutter container. You need a callback, which you interestingly already defined in your code, but not used. It's the javascriptChannels:
https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebView/javascriptChannels.html
It will create a JS window object with your chosen name, which you can then call from JS with your value. You get the value back in Flutter. Basically whole Cordova is built on such mechanism.
Some more practical suggestions:
give your channel as unique name as possible, to avoid namespace fight with other JS libraries. Definitely not "Print" like in the example.
the callback will most likely be asynchronous. Don't expect the WebView to drop everything just to deliver a value immediately in your Channel callback. It will most probably go on doing other things in JavaScript, and the callback will appear later.
Disclaimer: i have zero experience with Flutter, but i have tons of experience with WebView interoperability on iOS and Android. Please create a new issue for any further advanced Flutter questions you may want to ask now.

expo + react-native: There was a problem sending log messages

I am building a react-native app that I recently moved to expo. The app seems to display the expected screen, but before it completes, I am receiving the following error message: console.error: "There was a problem sending log messages to your development environment, {"name": "Error"}". When I view the expo browser screen I see the following stack trace when I click on the device:
node_modules/expo/build/logs/LogSerialization.js:146:14 in _captureConsoleStackTrace
node_modules/expo/build/logs/LogSerialization.js:41:24 in Object.serializeLogDataAsync$
node_modules/regenerator-runtime/runtime.js:62:39 in tryCatch
node_modules/regenerator-runtime/runtime.js:288:21 in Generator.invoke [as _invoke]
node_modules/regenerator-runtime/runtime.js:114:20 in Generator.prototype.(anonymous
node_modules/regenerator-runtime/runtime.js:62:39 in tryCatch
node_modules/regenerator-runtime/runtime.js:152:19 in invoke
node_modules/regenerator-runtime/runtime.js:187:10 in <unknown>
node_modules/promise/setimmediate/core.js:45:4 in tryCallTwo
node_modules/promise/setimmediate/core.js:200:12 in doResolve
Here is a screenshot of the error:
What does this error mean? I found some doc referring to removing console.log statements and removed the ones I had but that did not help.
This is due to the fact that the React native console logger CANNOT parse the JSON object coming from Axios.
I can guarantee that anyone who is having this error is not PARSING the JSON object before logging it to the console.
CODE THAT WILL GIVE THIS ERROR:
Axios.post(URL).then(function (response)
{
console.log("POST RESPONSE: "+response);
}
CODE THAT FIXES THIS ERROR:
Axios.post(URL).then(function (response)
{
console.log("POST RESPONSE: "+JSON.stringify(response));
}
I ran into this weird error as well this morning. I am developing in react native with Expo Client for an app I'm building with the popular MERN stack (mongoDB, Express, React Native and Node.js). I am mentioning that because I use a lot, I mean A LOT of console logs in the backend and this didn't cause me any problem thus far. So in my case, I was not sure if this error originated from any console.log I was using.
I checked the expo debugger's stacktrace in the console (in port 19001), because the red screen doesn't provide much info on the origin of the error (a lot of <unknown> in place of functions) and I saw that it had something to do with my actions functions and the payload I was sending to my reducer when I performed a specific action that was communicating with the backend. The backend's response was formatted like this:
payload: {
config: {
.
.
.
}
data: { the only part that i needed... }
headers: {
.
.
.
}
..other stuff from the response..
There's not much to notice above, but this:
The actual paylaod I was interested in is under the prop key data and was the only thing I needed from the response. BUT, in my ignorance I was sending everything to my reducer. So what I am saying is that I was sending a really big object as payload and I only needed a part of it. So when I did some destructuring and kept the data that I mentioned above, the error went away.
In conclusion, for others that may stumble across this "error" which isn't actually an error, because the app doesn't crash or anything, since you can dismiss the window and the app goes on, when you do some fetching from the server, make sure you keep only the data and not the whole response object, along with the meta from the call. It seems that redux-logger throws this because it doesn't like the structure of it.
To simplify all the answers above, This issue only happens when you log an object which is too big for console to display. So when ever logging the response from an API or Server be sure to add JSON.stringify(result).
This resolved the issue for me.
I have also ran into this issue but due to other causes.
BACKGROUND:
Project stack (Just what is important to the error) :
expo: ^34.0.1
react-native: SDK 34
react-navigation: 4.0.5
react-navigation-drawer: ^2.2.1
In this project I was not using react-redux or axios I'm actually using graphql , #apollo/react-hooks and apollo-boost to take care of network requests and local state management.
ANSWER:
As you can see in the BACKGROUND, I am using react-navigation. I was creating a drawer navigator with createDrawerNavigator according to the React Navigation API
I wanted to use the contentComponent property of the DrawerNavigatorConfig to create custom DrawerNavigatorItems.
I put and anonymous arrow function in the contentComponent property with the only argument of props.
THIS CAUSED THE ERROR:
I placed a console.log() inside the anonymous arrow function I mentioned above
I received the error on my iOS simulator that read:
`console.error: "There was a problem sending log messages to your development environment"
See my code below:
import {createDrawerNavigator, DrawerNavigatorItems} from "react-navigation-drawer";
import ProfileNavigator from "../Profile/Profile";
import Colors from "../../constants/colors";
import {AsyncStorage, Button, SafeAreaView, View} from "react-native";
import React from "react";
import {Logout} from "../Common";
import HomeNavigator from "../Home/Home";
const AppDrawerNavigator = createDrawerNavigator(
{
Profile: ProfileNavigator
},
{
contentOptions: {
activeTintColor: Colors.primary
},
contentComponent: props => {
console.log(props) // THIS IS THE ISSUE CAUSING THE ERROR!!!!!!
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerNavigatorItems {...props} />
<Button
title="Logout"
color={Colors.primary}
onPress={Logout}
/>
</SafeAreaView>
</View>
)
},
drawerType: 'slide',
unmountInactiveRoutes: true
}
)
export default AppDrawerNavigator
I got this error consistently when dumping the result of a fetch call to console like: console.log(result).
Once I used:
console.log(JSON.stringify(result))
the problem went away.
I had the same issue today and the fix was to add response.json()
fetch(endpoint, {
method: 'GET',
headers: {
Accept: 'application/json',
}
})
.then(response => response.json())
.then(response => {
console.log('response', response)
})
This is the problem that comes with console.log (In VSCode, Ctrl + Shift + F to search all then type console.log to find where it is).
Convert from
console.log(error.config);
to
console.log(JSON.stringify(error.config, null, 2));
(null, 2 is to keep the print pretty)
Objects being sent to console.log are causing the red screen. As others noted you need to stringify all objects.
For those who don't have time to update every console.log in their app, simply do a global replace of console.log with a new function name (we used global.ourLog) and use this code to look at every param and stringify if an object. This function was put in the first line of our App.js of our expo app.
// this routine corrects the red screen
// of death with expo logging
// by taking objects that are logged and ensuring
// they are converted to strings
global.ourLog = function() {
let s = ''
for ( let a of arguments ) {
if ( typeof a === 'string') {
s += a
} else if ( typeof a === 'number') {
s += a
} else {
s += JSON.stringify(a,null,2)
}
s += '\t'
}
console.log(s)
}
then use like any other console.log (or replace every console.log with that new function name).
global.ourLog( "a string", anObject, err)
Hope this helps someone, it saved us a ton of time.

React native android undefined is not a function works in IOS

Works in IOS and works in Android when the debugger is running, but doesn't work via Android Simulator. I get this message via react-native log-android and basically I am just having nothing returned to the screen:
12-02 10:39:58.511 22502 24204 W ReactNativeJS: TypeError: undefined is not a function (near '...}).flat()
Android Picture
IOS Picture
Here is the fetch function I am using:
import axios from 'axios';
export const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
return data;
} catch (error) {
console.log(error);
}
};
export default getData;
Inside of my componentDidMount, where I call the endpoint using the GetData function above:
componentDidMount() {
const teamsAPI = 'https://statsapi.web.nhl.com/api/v1/teams';
getData(teamsAPI).then(teams => {
const teamData = teams.teams
.map(({ id, name }) => ({
teamId: id,
teamName: name
}))
.flat()
this.setState({
teams: teamData
});
});
}
Everything has since been moved to REDUX, but I looked back at one of my branches today with the more basic code shared above and had the issue back then with this code as well. Unfortunately didn't realize all the differences with code compilations till now. Understand that the issue is probably because of 2 compilers, but have no idea how to approach the issue/ why there would be a type error in one and not the other.
It works with debugger I think due to what was mentioned here:
React Native behavior different in simulator / on device / with or without Chrome debugging
Edit: wanted to mention I've already done a cache reset and deleted the build folder and rebuilt
I tried out your code and the promise rejecting is happing for me in both Android and iOS. It is being caused by the .flat() removing it stops the promise rejection from occurring.
Looking at the data that you are mapping there there doesn't seem to be a need to flatten the data as it comes back as a array of objects with no other arrays inside it.
Could removing the .flat() be a possible solution for you?
You can see here for more information about .flat() and how it is still experimental array.prototype.flat is undefined in nodejs
I would also consider returning something from your getData function when it makes an error or perhaps use a promise with it that way you can handle an error.

How to open Other app from ReactNative?

How to open other apps (Gmail, Camera) from ReactNative. How can I pass data from current scene to other app?
I found this npm library react-native-app-link which can open other apps. This is based on deep linking, if you have any deep links then this library can help. This doesn't open apps just by giving the android package name or ios app id.
https://github.com/FiberJW/react-native-app-link
you can mange opening other apps using Linking
Code sample for opening the dialer
const urlToOpen = 'tel:1234567890';
Linking.openURL(urlToOpen);
You can refer to the official doc here, it just predefines some applications, which can be opened.
However, if the question is about to open just about any application, I hope there is no solution till now.
react-native-app-link has some redundant config (e.g. appStoreLocale parameter), so I wrote my own realization using their code:
import { Alert, Platform, ToastAndroid } from 'react-native';
const isIos = Platform.OS === 'ios';
const showNotification = (text) => isIos
? Alert.alert(text)
: ToastAndroid.show(text, ToastAndroid.SHORT);
const openApp = ({ url, appStoreId, playMarketId, name }) => {
Linking.openURL(url).catch(err => {
if (err.code === 'EUNSPECIFIED') {
Linking.openURL(
isIos
? `https://apps.apple.com/app/id${appStoreId}`
: `https://play.google.com/store/apps/details?id=${playMarketId}`,
);
} else {
showNotification(`Can't open ${name} app`);
}
});
};
It tries to open the app by the specified link, and if the user doesn't have such one, it opens its page in AppStore or Play Market.

How to create a generic "create photo" code for both iPhone and Android using Appcelerator?

I am trying to create an application that is capable of creating photos on both Android and iPhone using Appcelerator. The functionality should launch default photo API, create a photo, allow user to either agree with photo, or cancel it, and on successful result save it on the memory card. It is not necessary that photos should be automatically added to the Gallery.
Currently I am using this code which works perfectly for Android :
Rf.media.photo = {
key: 'photo',
title: 'Photo',
extension: 'jpg',
type: 'image/jpeg',
create: function(created) {
Ti.Media.showCamera({
// TODO: disallow video for ios
animated: false,
saveToPhotoGallery: false,
showControls: true,
success: function(media_item) {
var name = Rf.util.timestamp() + '.' + Rf.media.photo.extension;
Rf.write_to_new_file(name, media_item.media, function(file) {
created(file);
});
},
});
},
};
I am looking for ways to tweek this code, so it would work also for iPhone. At the moment it is unresponsive when tested on iPhone 4.
Anyone knows whats wrong with it?
take a look at the kitchenSink examples for photo and photo gallery, they provide a pretty complete example

Categories

Resources