Has an item been seen - React Native - react-native

I am trying to update the state of an item in a JSON file (isRead) once an application has been opened. I am using react native but can not find any documentation on the subject. Is there such functions?
I am not sure whether I need to use call backs or anything like that, as it is a simple app, loading the files locally.
My Logic is like this:
if(isRead == false){
Render i
}
else{
Render i++
}

You can use setState.I will show for you counter example about subject.You should review following code.
import React,{Component} from "react"
import {View,TouchableOpacity,Text} from "react-native"
class Test extends Component{
state ={
count = 0
}
changeCount(){
this.setState({count:this.state.count++})
}
render(){
return(
<View>
<TouchableOpacity onPress={this.changeCount.bind(this)}/>
<Text>{this.state.count}</Text>
<View/>)
}
}

Related

Query in react native about sliding up panel

In React Native iOS, I would like to slide in and out of a like in the following picture.
So I installed this https://github.com/octopitus/rn-sliding-up-panel for ease.
but this error is showing =>
i cant understand whats wrong, I am new to react native. Please Help!
You cannot access variable called _panel from this object because you are inside a function itself. besides you are using function based react, in order to create a reference check useRef() hook or switch to class based component and then you can use this._panel;
smthg like this:
function AccessingElement() {
const elementRef = useRef();
const onPress = () => {
// e.g
elementRef.current.show();
}
return (
<View ref={elementRef}>
...child views
</View>
);
}

Fetching Data From Server Using iOS Device in React Native

I have just started learning React Native and development for mobile devices. One of the things I've tried is using fetch API to get data from http://jsonplaceholder.typicode.com/posts
The App.js file is given below:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default function App() {
const [firstLoad, setLoad] = React.useState(true);
const [data, upDateData] = React.useState([]);
let isLoading = true;
async function sampleFunc() {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let body = await response.json();
upDateData(body);
}
if (firstLoad) {
sampleFunc();
setLoad(false);
}
if (data.length > 0) isLoading = false;
const posts = data.map(post => (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
));
return (
<View style={styles.container}>
{isLoading ?
<Text>Loading</Text> :
<Text>{posts}</Text>
}
</View>
);
}
Nothing fancy is going on here, just making an https request to the server to get posts. While the data is being transferred, the Loading label is being displayed, after that, all fetched posts are rendered on the page.
I am using Expo, and everything works fine when I run it in the browser, but when I scan the QR code, Expo app opens, the Loading message is displayed for a couple of seconds, and then the app crashes.
I may be doing something here that is typical of regular React and is not used in React Native. It is just strange that it would work on my computer and not the phone. Any suggestions would be greatly appreciated. Thank you in advance!
You cannot have text outside of Text components in react-native.
In your example, in the post function, you use the h1 and p tags, which are not supported by react-native.
The fix here is to make sure that those texts are inside Text components, you can have styling set to those to make them look closer to what you want.
You can refer the docs on how to create custom styles.
const posts = data.map(post => (
<View>
<Text>{post.title}</Text>
<Text>{post.body}</Text>
</View>
));
To debug similar issues in the future, you should be getting a red flashing screen with the exception. (Maybe it doesn't appear when running on Expo)

react native Webview Process Terminated

Im using react native to show a local HTML on a web view,
I have noticed that some times randomly, the webView crashes, and I get the message on console:
Webview Process Terminated
I have searched about it, but cannot find any answers?
what is that? why is happening? how to avoid it or reload web view after that error?
<WebView
style={styles.webContainer}
originWhitelist={['*']}
source={isAndroid ? {uri:'file:///android_asset/binaura.html'} : HTML_FILE}
javaScriptEnabled={true}
domStorageEnabled={true}
/>
If by "WebView" you mean react-native-webview:
This happens on iOS if the WebView is using too many resources, and results in either the WebView crashing (showing a blank white page) or the app freezing.
There is a callback property, onContentProcessDidTerminate (introduced in this PR), that you can use to listen for termination and force a reload of the WebView by updating its key. It's a bit of a hack, but it works.
Usage example:
class MyComponent extends Component {
state = {
webviewKey: 0,
}
reload() {
this.setState({
webviewKey: this.state.webviewKey + 1,
})
}
render() {
return (
<WebView
key={this.state.webviewKey}
onContentProcessDidTerminate={this.reload}
/>
)
}
}
#pjivers answer put us on the right track but the current react-native-webview already has a reload() method you can use. You only need a bit of ref setup to call it:
class MyComponent extends Component {
constructor(props) {
super(props);
this.webViewRef = React.createRef();
}
render() {
return (
<WebView
ref={this.webViewRef}
onContentProcessDidTerminate={this.webViewRef.current?.reload}
/>
)
}
}

how to disable YellowBox in react-native totally in a native way ? not in JavaScript

I know console.disableYellowBox = true could be answer. But I want ban it with all my control because my App has multiple package and I do not want to use console.disableYellowBox = true in every package.
is there any way to achieve this by set a config in shaking bar ?
I tried with the new React version replacing the import to:
import { LogBox } from "react-native";
and adding this line inside App.js
LogBox.ignoreAllLogs();
And it's working good for me.
You have multiple way's in doing that, which is not recommended since you want to know what's causing these warnings and sometimes it's important informations you need to know, here is some of the ways you can do
Warnings will be displayed on screen with a yellow background. These
alerts are known as YellowBoxes. Click on the alerts to show more
information or to dismiss them.
As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using
console.disableYellowBox = true;
using ignore
console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
ignoredYellowBox allows you to ignore certain warnings as you can see in the example above.
using disableYellowBox
console.disableYellowBox = true;
disableYellowBox allows you to disable it completely from your app.
however both these ways you need to use inside App.js before you render you app.
example:
import React, { Component } from "react";
import { View } from "react-native";
//console.disableYellowBox = true;
//OR
//console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
export default class App extends Component {
render() {
return (
<View>
{/*Your Code will be here*/}
</View>
);
}
}
Take a look at Debugging React Native to learn more about YellowBox
// RN >= 0.52
import {YellowBox} from 'react-native';
YellowBox.ignoreWarnings(['Warning: ReactNative.createElement']);
// RN < 0.52
console.ignoredYellowBox = ['Warning: ReactNative.createElement'];

React Native: How can I use the DeviceInfo isTablet() method to conditionally apply a style to an element?

I am trying to adapt the design of my app to tablet and one way to detect if the app is running on a tablet is by using the DeviceInfo module in particular the isTablet() method. How can I use this method to conditionally apply styles to an element?
Here is what I am trying to do at the moment:
import { checkIfDeviceIsTablet } from './helper-functions';
<View style={[styles.wrapper, checkIfDeviceIsTablet() === true ? styles.wrapperTablet : {}]}>
{contents}
</View>
The checkIfDeviceIsTablet() function is as follows:
import DeviceInfo from 'react-native-device-info';
function checkIfDeviceIsTablet() {
DeviceInfo.isTablet().then(isTablet => {
return isTablet;
});
}
The issue is that when the component loads the checkIfDeviceIsTablet() method returns a promise as opposed to the expected true/false value and so the conditional styles are not applied when the app is run on a tablet. I tried turning the function into an async/await format with a try/catch but the result is the same.
I would use React Native's own Platform.isPad function but the app must also work on Android.
Any help is appreciated.
I would recommend calling DeviceInfo.isTablet() only once at the beginning of your app. You can store the result globally, and then later on you can check the type without having to deal with async promises.
To store the type globally, your options are:
A global variable
React's Context API
A static property on a class (if using ES6+)
Some sort of global state management solution like Redux
You still have to deal with the initial async problem, since the first call to DeviceInfo.isTablet() will return an async promise.
I'd recommend looking into React's Context API.
Here's a rough example:
render() {
return (
<DeviceInfoContext.Consumer>
{ ({ isTablet }) => (
<Text>Is this a tablet? {isTablet}</Text>
) }
</DeviceInfoContext.Consumer>
)
}
And your DeviceInfoContext class would look something like this:
class DeviceInfoContext extends React.Component {
state = {
isTablet: false
}
componentDidMount() {
Device.IsTablet().then(result => this.setState({ isTablet: result }))
}
render() {
return (
this.props.children({ isTablet: this.state.isTablet })
)
}
}
This is just a rough example. You can learn more about the Context API in the docs
Me too had some troubles with the breaking changes of react native 0.5xx to 0.6xx. The library for device detection change it structure to promises. A paintful.
This library save the day, the installation and use is very easy.
https://github.com/m0ngr31/react-native-device-detection
import { isTablet } from 'react-native-device-detection;
// isTablet is a boolean. Return false o true immediately
//So ...
import styled from 'styled-components/native';
import theme from 'styled-theming';
import { isTablet } from 'react-native-device-detection';
const CoverPageDateText = styled.Text`
font-size: ${isTablet ? 23 : 17};
color: gray;
padding-bottom: 9;
`