Fetching Data From Server Using iOS Device in React Native - 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)

Related

How to know component is ready to render?

I am new in React-Native and I am stuck at one place to do in React-Native.
This is my one component :-
const ConentQR = (
content: string,
logo: Image.propTypes.source,
logoSize: number,
) => {
return (
<QRCode
color={Colors.DARK_PURPLE}
content={content}
codeStyle={'dot'}
outerEyeStyle={'diamond'}
logo={logo}
logoSize={logoSize}
backgroundColor={'transparent'}
/>
);
};
The problem is I am facing in react native,This component (<QRCode) take some time to generate QR, so how I can put this block in any background thread so that I can show loader to user until it get prepared. I am getting stuck at this place and unable to resolve that for while.
Please help anyone
You could use the InteractionManager to schedule tasks in the background
import { InteractionManager } from 'react-native'
const ConentQR = (
content: string,
logo: Image.propTypes.source,
logoSize: number,
) => {
// Use a state variable to track the QR code
const [qrCode, setQrCode] = useState(null)
// Use the InteractionManager to run the generation process in the background
InteractionManager.runAfterInteractions(() => {
// Generate the QR code in the background
const qrCode = generateQRCode(content, logo, logoSize)
setQrCode(qrCode)
})
// Show a loading spinner while the QR code is generated
// so the user knows something is happening in the background
if (!qrCode) {
return <ActivityIndicator />
}
// Render the QR code when it's ready
return <QRCode {...qrCode} />
}
I am using useState to keep track on the qr code and InteractionManager.runAfterInteractions to schedule the generation in the background. If the qr code is not ready it displays a loader. The generation happens in the generateQRCode() function.

Expo React Native - How come returning null on App.js initialization function is good behaviour?

This is mainly a comprehension problem:
Considering the following expo docs, which aren't explaining what is going on under the hood,
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
SplashScreen.preventAutoHideAsync();
export default function App() {
const [fontsLoaded] = useFonts({
'Inter-Black': require('./assets/fonts/Inter-Black.otf'),
});
const onLayoutRootView = useCallback(async () => {
if (fontsLoaded) {
await SplashScreen.hideAsync();
}
}, [fontsLoaded]);
if (!fontsLoaded) {
return null;
}
return (
// Your app tree there.
);
}
What is going on here from my understanding is that you prevent the splashscreen from going away while you retrieve certain assets, like fonts.
When you do have your assets, you make the splashscreen go away and you launch your app by returning your components' tree.
The part I don't understand is why is it ok to return null if the fonts don't get loaded?
Since it is the initialization function, my mind want to think that if you return null to it, your app doesn't start and the user will be left wondering why...
Is there an explanation, a logic behind the hood actually refreshing something to recheck until it is ok and the assets are indeed loaded or something I don't know?
I know I have the case of my app not starting correctly every time right now and I'm wondering if this "return null" on the App.js function could be the culprit.

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>
);
}

RGB function in react

I've recently started to work on React Native. I'm trying to create a simple function for generating Random Colors. The problem I am facing is that my IDE says that the variables that I have declared are not in use. Hence, the color is not generated on the my device's screen. Can anyone kindly have a look at it tell me what am I doing wrong?
P.S: I tried setting the color manually in the "View state" by writing "backgroundColor: 'rgb(0,255,0)'}}/>" and it successfully worked. The only time I am facing a problem is when I am trying to use the randomRGB function.
import React from 'react';
import {StyleSheet, Button, View, Text} from 'react-native';
const ColorScreen = () => {
return(
<View style={{height:100 , width:100, backgroundColor:randomRgb()}}/>
}
const randomRgb = () =>{
const red = Math.floor(Math.random()*256);
const green = Math.floor(Math.random()*256);
const blue = Math.floor(Math.random()*256);
return 'rgb(${red}, ${green}, ${blue})';
};
export default ColorScreen;
Nvm guys. I'm an idiot. I was using quote instead of backquotes. Yeah stupid I know, but I wouldn't delete this because there may be other people like me. So, use " ` " instead.

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'];