React Native Android lag during animation - react-native

I experience the lag during transition animation when Navigator goes to below scene ShiftEdit. Animation starts immediately but it stops for a millisecond. InteractionManager is used to postpone rendering of four picker components. Every picker component has list of items that is built from an array. There is lots of items. Is it possible that this is calculated even when picker component isn't rendered yet in ShiftEdit and this is the reason of the lag? Could you help me please?
'use strict'
import React, {View, Text, StyleSheet, InteractionManager, TouchableOpacity} from 'react-native';
import { connect } from 'react-redux';
import Spinner from 'react-native-spinkit';
import StyleCommon from '../styles';
import TimePicker from '../components/time-picker';
import ColorPicker from '../components/color-picker';
import LabelPicker from '../components/label-picker';
class ShiftEdit extends React.Component {
constructor(props) {
super(props);
this.state = {
isReady: false,
shiftId: '',
startHour: '',
endHour: '',
color: '',
}
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
this.setState({isReady: true});
});
}
onChangeItem = (label, val) => {
let data = {};
data[label] = val;
this.setState(data);
}
renderPlaceholder() {
return (
<View style={styles.container}>
<Text>Loading...</Text>
</View>
)
}
render() {
if (!this.state.isReady) {
return this.renderPlaceholder();
}
return (
<View style={{flex:1, flexDirection: 'column'}}>
<TimePicker label={'Start hour'} value={this.state.startHour} onChange={this.onChangeItem.bind(this, 'startHour')} />
<TimePicker label={'End hour'} value={this.state.endHour} onChange={this.onChangeItem.bind(this, 'endHour')} />
<ColorPicker label={'Color'} value={this.state.color} onChange={this.onChangeItem.bind(this, 'color')} />
<LabelPicker label={'Shift ID'} value={this.state.shiftId} onChange={this.onChangeItem.bind(this, 'shiftId')} />
</View>
)
}
};
I tried to control animation registration as Chris suggested but it still the same:
onPress = () => {
let handle = InteractionManager.createInteractionHandle();
this.props.navigator.push({component: 'shiftedit'});
InteractionManager.clearInteractionHandle(handle);
}

Actually this is the only solution that works for me now:
componentDidMount() {
// InteractionManager.runAfterInteractions(() => {
// this.setState({isReady: true});
// })
setTimeout(() => {
this.setState({isReady: true});
}, 75);
}
but I'd rather use InteractionManager...

Here's a wild guess as I've no experience with InteractionManager directly. But after looking over the Interaction Manager Docs I noticed that there's a way to register animations. So, my guess is that the Navigator's animations haven't been properly registered. So maybe try something like this...
var handle = InteractionManager.createInteractionHandle();
// run your navigator.push() here... (`runAfterInteractions` tasks are queued)
// later, on animation completion:
InteractionManager.clearInteractionHandle(handle);
// queued tasks run if all handles were cleared
Hope that helps!

Also, keep in mind that if you're running the React Native Debugger while testing your app, React Native animations will appear jittery on Android.
That's been my experience.
https://github.com/jhen0409/react-native-debugger

Related

Warning: React has detected a change in the order of Hooks

I have run into this error in my code, and don't really know how to solve it, can anyone help me?
I get the following error message:
ERROR Warning: React has detected a change in the order of Hooks called by ScreenA. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
import React, { useCallback, useEffect, useState } from "react";
import { View, Text, StyleSheet, Pressable } from "react-native";
import { useNavigation } from '#react-navigation/native';
import { DancingScript_400Regular } from "#expo-google-fonts/dancing-script";
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
export default function ScreenA({ route }) {
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
// Keep the splash screen visible while we fetch resources
await SplashScreen.preventAutoHideAsync();
// Pre-load fonts, make any API calls you need to do here
await Font.loadAsync({ DancingScript_400Regular });
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// This tells the splash screen to hide immediately! If we call this after
// `setAppIsReady`, then we may see a blank screen while the app is
// loading its initial state and rendering its first pixels. So instead,
// we hide the splash screen once we know the root view has already
// performed layout.
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
const navigation = useNavigation();
const onPressHandler = () => {
// navigation.navigate('Screen_B', { itemName: 'Item from Screen A', itemID: 12 });
}
return (
<View style={styles.body} onLayout={onLayoutRootView}>
<Text style={styles.text}>
Screen A
</Text>
<Pressable
onPress={onPressHandler}
style={({ pressed }) => ({ backgroundColor: pressed ? '#ddd' : '#0f0' })}
>
<Text style={styles.text}>
Go To Screen B
</Text>
</Pressable>
<Text style={styles.text}>{route.params?.Message}</Text>
</View>
)
}
const styles = StyleSheet.create({
body: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 40,
margin: 10,
fontFamily: 'DancingScript_400Regular'
}
})
I have read the rules of hooks: https://reactjs.org/docs/hooks-rules.html
The output is correct, but i want to fix this error before i add more additions to the app
You need to move useNavigation use before early returns.
Instead, always use Hooks at the top level of your React function, before any early returns.
The key is you need to call all the hooks in the exact same order on every component lifecycle update, which means you can't use hooks with conditional operators or loop statements such as:
if (customValue) useHook();
// or
for (let i = 0; i< customValue; i++) useHook();
// or
if (customValue) return;
useHook();
So moving const navigation = useNavigation(); before if (!appIsReady) {return null;}, should solve your problem:
export default function ScreenA({ route }) {
const [appIsReady, setAppIsReady] = useState(false);
const navigation = useNavigation();
// ...
}

React native How to execute function every time when i open page

I need to send request every time when i open page. Currently when i access page first time after load the app everything is ok, but if i go to another page and back after that request is not send it again.
You have to add focus listener so when you go back, It will refresh the data like
import * as React from 'react';
import { View } from 'react-native';
function AppScreen({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action and update data
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}
source : https://reactnavigation.org/docs/function-after-focusing-screen/
Here you go, example for a class based and functional based component to run something on every load of the screen.
import React, { useEffect } from "react";
import {View} from 'react-native'
//Functional Component
const App = () =>
{
useEffect(() =>
{
myAction();
}, [])
return (
<View>
</View>
);
}
//Class based Component
class App extends Component
{
componentDidMount()
{
this.myAction();
}
render()
{
return(
<View>
</View>
)
}
}

How to change react native app layout from api

I have developed an store app, my boss wants a feature that from wordpress panel select predefined layout to change the whole design and choose which category to be first or .... .
I have created all designs and components that needed, but I do not know how to change app layout that I recieved from api, is there any code or help for that. This change is not about color , its about changing whole home page app layout
Sorry for my english
Here is a simple example that you could implement.
You'll need to create custom complete components for each layout for the homepage.
Then you'll need to call the Wordpress API to get the layout name that needs to be displayed.
import React, { PureComponent } from 'react';
import { AppRegistry } from 'react-native';
import Layout1 from './components/Home/Layout1';
import Layout2 from './components/Home/Layout2';
import Layout3 from './components/Home/Layout3';
import Layout4 from './components/Home/Layout4';
import Loading from './components/Loading';
class HomePage extends PureComponent {
constructor(props) {
super(props);
this.state = {
layout: null
};
}
async componentDidMount() {
const response = await fetch('https://example.com/wp-json/whatever-api-endpoint')
.then(r => r.json());
this.setState({
layout: response
});
}
getContentElement = () => {
switch (this.state.layout) {
case 'layout_1': return <Layout1 />;
case 'layout_2': return <Layout2 />;
case 'layout_3': return <Layout3 />;
case 'layout_4': return <Layout4 />;
default: return <Loading />
}
};
render() {
const contentElement = this.getContentElement();
return (
<View>
{contentElement}
</View>
);
}
}
AppRegistry.registerComponent('MyApp', () => HomePage);

Is there a way to read the options before use the mergeOptions function in react native navigation v2?

Is there a way to read the options before using the mergeOptions function.
I'm trying to add a sideMenu that opens and closes with the same button. But to handle that logic, Instead of making use of redux, I want to read the options before the merge, so I can simply do something like visible: !pastVisible.
navigationButtonPressed({ buttonId }) {
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
'left': {
visible: false
}
}
});
console.log(`Se presiono ${buttonId}`);
}
So basically I want to read the value of the visible option before changed it.
By now, I can only achieve this using redux.
import React, {Component} from 'react';
import {View, Text} from 'react-native';
import { Navigation } from 'react-native-navigation';
import { connect } from 'react-redux';
import { toggleSideMenu } from './../../store/actions/index';
class SideDrawer extends Component {
constructor(props) {
super(props);
Navigation.events().registerComponentDidDisappearListener(({ componentId }) => {
this.props.toggleSideMenu(false);
});
}
render() {
return (
<View>
<Text>This is the sidedrawer</Text>
</View>
);
}
}
const mapDispatchToProps = dispatch => {
return {
toggleSideMenu: (visible) => dispatch(toggleSideMenu(visible))
};
};
export default connect(null, mapDispatchToProps)(SideDrawer);
Then I just add the listeners to the sidemenu component. Depending on the case, I update the current state of the component (visible or not).
Finally on the components where I want to use the side drawer button I just implement the navigationButtenPressed method. Then I just call the reducer to know the current visible state and toggled it.
navigationButtonPressed({ buttonId }) {
const visible = !this.props.sideMenu;
Navigation.mergeOptions(this.props.componentId, {
sideMenu: {
'left': {
visible: visible
}
}
});
this.props.toggleSideMenu(visible);
}
If there is a more easy way to achieve this I'll be glad to know about it.

Keyboard listener is running more then once

Hey I'm trying to create an event that will fire when the keyboard shows up but the function is firing more then once, I don't know why ..
import React, { Component } from 'react';
import { Keyboard, Alert, View, TextInput } from 'react-native';
export default class App extends Component {
constructor(props: any) {
super(props);
this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
}
componentWillUnmount() {
this.kbDidShowListener.remove();
}
render() {
return (
<View style={{ marginTop: 30 }}>
<TextInput />
</View>
);
}
}
here is an expo for the example (you will see the alert more then once)
https://snack.expo.io/H1DHaIdgM
p.s I'm working on Android.
thanks!
The render function does not run only once. Usually refreshes multiple times too, while calculating the state and props. That could explain the issue.
If you want to be sure, try adding a console too inside the render method, to see if the numbers match.
Actually, another thing I am thinking. Try moving the code to the componentWillMount or componentDidMount
componentDidMount(){
this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
}