Item Component Collapsed in Flatlist when move to next

This issue has been created since 2022-11-16.

Description

I am trying to create a slider using a flatlist; it works fine on most devices, but on the iPhone 12, it misbehaves. The first index item appears correctly, but when I move to the next item, the item container view collapses and all items move to the top of the screen. I have tried both vertical and horizontal scrolling directions. Is there anyone who can assist me in resolving this? I have attached some files for your reference.

phone.number.login.--.still.zoom.in.problem.mp4

iPhone 12 device information

Version

0.64.2

Output of npx react-native info

System:
OS: macOS 11.6
CPU: (12) x64 Intel(R) Core(TM) i5-10400 CPU @ 2.90GHz
Memory: 231.70 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 19.0.1 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 8.19.2 - /usr/local/bin/npm
Watchman: 2022.11.07.00 - /usr/local/bin/watchman
Managers:
CocoaPods: 1.11.2 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 21.2, iOS 15.2, macOS 12.1, tvOS 15.2, watchOS 8.3
Android SDK:
API Levels: 23, 25, 28, 30, 31, 32
Build Tools: 29.0.2, 30.0.0, 30.0.2, 30.0.3, 31.0.0, 32.0.0
System Images: android-30 | Google Play Intel x86 Atom
Android NDK: Not Found
IDEs:
Android Studio: 2021.2 AI-212.5712.43.2112.8815526
Xcode: 13.2.1/13C100 - /usr/bin/xcodebuild
Languages:
Java: 11.0.15 - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: ^17.0.2 => 17.0.2
react-native: ^0.64.2 => 0.64.2
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

Steps to reproduce

create a flatlist from the example code given.

Snack, code example, screenshot, or link to a repository

import React, {useContext, useEffect, useRef, useState} from 'react';
import {
View,
SafeAreaView,
FlatList,
TouchableOpacity,
Image,
KeyboardAvoidingView,
Keyboard,
ActivityIndicator,
StyleSheet,
} from 'react-native';
import {useDispatch, useSelector} from 'react-redux';
import {getFilterIds} from '../../../Actions/FeedActions';
import AppImages from '../../../Theme/AppImages';
import CommonStyle from '../../../Theme/CommonStyle';
import {
currentEnv,
isIOS,
phoneNoVerifyHeaderImages,
phoneNoVerifyScreens,
STORAGE,
width,
} from '../../../Utils/Constant';
import {
CustomPhoneInput,
CustomText,
CustomTextInput,
OtpInput,
PaginatedHeader,
} from '../../CommonComponent';
import {CommonActions} from '@react-navigation/native';
import {getErrorMessage, isValidEmail, showToast} from '../../../Utils/Helper';
import {AppContext} from '../../../AppContext';
import {
addFCMToken,
resendCode,
userLogin,
userVerify,
} from '../../../Services/UserService';
import {updateUserDetail} from '../../../Actions/UserActions';
import {getItemFromStorage, setItemInStorage} from '../../../Utils/Storage';
import {ApiConfig} from '../../../ApiConfig';
import {getOnboardData} from '../../../Actions/OnboardActions';
import DeviceInfo from 'react-native-device-info';

let count = 0;

const VerifyPhone = props => {
const {
route: {params},
} = props;
const {appTheme} = useContext(AppContext);
const {
flexContainer,
bottomContainer,
rowCenter,
errorInput,
verificationText,
flexStyle,
} = CommonStyle;
const {itemContainer, titleText, loader, resendContainer} = styles;
const {navigation} = props;
const {user} = useSelector(state => state.user);
const [listIndex, setListIndex] = useState(params?.index ? params.index : 0);
const [error, setError] = useState({});
const [hasError, setHasError] = useState({
email: false,
code: false,
phone: false,
});
const [toggle, setToggle] = useState(false);
const [userData, setUserData] = useState({
email: user?.email || '',
phone: user?.phone || '',
code: '',
unmaskedPhone: user?.unmaskedPhone || '',
countryCode: user?.countryCode || '',
});
const [sendCode, setSendCode] = useState(false);
const dispatch = useDispatch();
let flatListRef = useRef('');

useEffect(() => {
count = 0;
dispatch(getOnboardData());
}, []);

const onTextChange = (key, text, isValid, unmaskedNo, countryCode) => {
if (key && text) {
userData[key] = text;
if (unmaskedNo && countryCode) {
userData.unmaskedPhone = unmaskedNo;
userData.countryCode = countryCode;
}
setUserData(userData);
if (key === 'email' && listIndex === 0 && !params?.index) {
if (!isValidEmail(text)) {
setErrorData(key, 'Enter valid email.', true);
} else if (isValidEmail(text)) {
setErrorData(key, '', false);
}
}

  if (key === 'phone' && listIndex === 1) {
    if (!isValid) {
      setErrorData(key, 'Enter valid phone number.', true);
    } else {
      setErrorData(key, '', false);
    }
  }

  if (key === 'code' && listIndex === 2) {
    setErrorData(key, '', false);
  }
}

};

const setErrorData = (key, msg, value) => {
let errorData = error;
let hasErrorData = hasError;
errorData[key] = msg;
hasErrorData[key] = value;
setHasError(hasErrorData);
setError(errorData);
setToggle(!toggle);
};

const navigateToRoute = (route, params = {}) => {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{name: route, params: params}],
}),
);
};

const getComponentFromType = (item, index) => {
if (item.type === 'textInput') {
return (
<CustomTextInput
placeholder={item.placeholder}
keyboardType={item.keyboardType}
onTextChange={text => {
onTextChange(item.key, text);
}}
value={user[item.key]}
autoCapitalize={'none'}
/>
);
} else if (item.type === 'phoneInput') {
return (
<CustomPhoneInput
onTextChange={(text, isVerified, unmaskedNo, countryCode) => {
onTextChange(item.key, text, isVerified, unmaskedNo, countryCode);
}}
userData={userData}
/>
);
} else {
return (
<OtpInput
digits={6}
value={userData.code}
onChangeOtp={text => onTextChange(item.key, text)}
/>
);
}
};

const updateStorage = async data => {
setItemInStorage('token', data?.token);
ApiConfig.token = data.token;
ApiConfig.streamKey = data.user.streamAppKey;
ApiConfig.streamToken = data.user.streamToken;
};

const clearOTP = () => {
userData.code = '';
error.code = '';
hasError.code = '';
setUserData(userData);
setError(error);
setHasError(hasError);
};

const registerUser = async () => {
try {
if (count === 0) {
count = count + 1;
let registerData = userData;
if (user.provider) {
registerData.provider = user.provider;
registerData.providerId = user.providerId;
}
registerData.register = true;
console.log('registerData', registerData);
const response = await userLogin(registerData);
if (response.status === 'success') {
count = 0;
moveToNext();
// ApiConfig.token = response.data.userItem.activationToken;
// setItemInStorage('token', response.data.userItem.activationToken);
// dispatch(updateUserDetail(response.data.userItem));
// showToast(response.data.code);
}
}
} catch (err) {
if (err?.response?.data) {
count = 0;
setErrorData('phone', getErrorMessage(err), true);
}
}
};

const updateFCMToken = async () => {
const localToken = await getItemFromStorage(STORAGE.fcmToken);
console.log('localToken', localToken);
try {
if (localToken) {
const deviceId = await DeviceInfo.getDeviceId();
const data = {
token: localToken,
platform: isIOS ? 'ios' : 'android',
environment: currentEnv,
deviceId: deviceId,
};
console.log('data register firebase', data);
const repoonse = await addFCMToken(data);
console.log('repoonse', repoonse);
}
} catch (e) {
console.log(e);
}
};

const verifyUser = async () => {
try {
if (count === 0) {
count = count + 1;
let verificationData = userData;
verificationData.register = true;
console.log('verificationData', verificationData);
let response = await userVerify(verificationData);
if (response.status === 'success') {
console.log('response', response);
updateStorage(response.data);
ApiConfig.token = response.data.user.activationToken;
setItemInStorage('token', response.data.user.activationToken);
dispatch(
updateUserDetail({
...userData,
...response?.data?.user,
}),
);
if (response?.data?.user?.isProfileCompleted) {
makeTogetherCall(response?.data?.user);
showToast(
'Phone number already exists. Redirecting to together feeds.',
);
updateFCMToken();
navigateToRoute('Home');
} else {
showToast(response?.message);
navigateToRoute('SignUp');
}
}
}
} catch (err) {
if (err?.response?.data) {
count = 0;
userData.code = '';
setUserData(userData);
setErrorData('code', getErrorMessage(err), true);
}
}
};

const makeTogetherCall = userObj => {
dispatch(getFilterIds({user: userObj}));
};

const moveToNext = () => {
flatListRef?.scrollToIndex({index: listIndex + 1});
setListIndex(listIndex + 1);
};

const scrollToNext = () => {
Keyboard.dismiss();
if (listIndex === 1) {
registerUser();
} else if (listIndex === 2) {
console.log('asdfasdfadsf');
verifyUser();
} else {
moveToNext();
}
};

const scrollToPrevious = () => {
count = 0;
Keyboard.dismiss();
if (listIndex !== 0) {
if (listIndex === 2) {
clearOTP();
}
flatListRef?.scrollToIndex({index: listIndex - 1});
setListIndex(listIndex - 1);
} else {
navigation.goBack();
}
};

const checkError = () => {
let key =
(listIndex !== 0 && ((listIndex === 1 && 'phone') || 'code')) || 'email';

if (key !== 'phone') {
  let condition =
    key === 'email'
      ? hasError[key] || !userData[key]
      : hasError[key] || !userData[key] || userData[key].length !== 6;
  if (condition) {
    return true;
  }
  return false;
} else {
  if (hasError[key] || !userData.unmaskedPhone || !userData.countryCode) {
    return true;
  }
  return false;
}

};

const resendOTP = async () => {
try {
console.log(userData);
setSendCode(true);
const data = {phone: userData.phone, register: true};
const response = await resendCode(data);
if (response.status === 'success') {
clearOTP();
setSendCode(false);
// showToast(response.data.code);
}
} catch (error) {
setSendCode(false);
}
};

const renderItem = ({item, index}) => {
return (


{item.title}

{getComponentFromType(item, index)}
{(hasError[item.key] && (

{error[item.key]}

)) ||
null}
{(item.key === 'code' && (
<TouchableOpacity
style={[rowCenter, resendContainer]}
onPress={() => resendOTP()}>
{(sendCode && (
<ActivityIndicator
size={'small'}
color={appTheme.theme}
style={loader}
/>
)) ||
null}

{sendCode
? 'Sending Verification Code'
: 'Resend Verification Code'}


)) ||
null}

);
};

return (

<KeyboardAvoidingView
behavior={'padding'}
style={flexStyle}
keyboardVerticalOffset={isIOS ? '' : -500}>
<PaginatedHeader
headerImages={phoneNoVerifyHeaderImages}
activeIndex={listIndex}
onPressBack={() => {
scrollToPrevious();
}}
/>

<FlatList
showsHorizontalScrollIndicator={false}
data={phoneNoVerifyScreens}
renderItem={renderItem}
keyExtractor={item => item.id}
horizontal={true}
scrollEnabled={false}
ref={ref => {
flatListRef = ref;
}}
initialScrollIndex={params?.index ? params?.index : 0}
keyboardShouldPersistTaps={'always'}
/>

{(!checkError() && (
<TouchableOpacity
onPress={() => {
scrollToNext();
}}>
<Image
source={{uri: AppImages.next}}
style={CommonStyle.nextImage}
resizeMode="contain"
/>

)) || (
<Image
source={{uri: AppImages.disabled}}
style={CommonStyle.nextImage}
resizeMode="contain"
/>
)}




);
};

const styles = StyleSheet.create({
itemContainer: {
flex: 1,
width: width,
paddingHorizontal: 16,
marginTop: '10%',
},
titleText: {
marginBottom: '10%',
},
loader: {
marginRight: 10,
},
resendContainer: {
marginTop: 10,
},
});

export default VerifyPhone;

More Details About Repo
Owner Name facebook
Repo Name react-native
Full Name facebook/react-native
Language JavaScript
Created Date 2015-01-09
Updated Date 2022-12-10
Star Count 106395
Watcher Count 3660
Fork Count 22685
Issue Count 2288

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
[Question] Secondary & Tertiary tuning before Primary 3 2021-10-24 2022-10-08
Specifiche tecniche versione 1.6.2 (aggiornate il 23 nov 2020) 7 2021-02-09 2022-08-28
DecimalRuleExtensions 0 2021-02-04 2022-12-04
Nuovo valore "DPU" in TipoResa (al posto di DAT) 1 2021-01-18 2022-10-03
When call DiscoverDevices() -- System.Runtime.InteropServices.COMException: 'A method was called at an unexpected time.' 1 2022-08-16 2022-11-09
Display AAGUID on screen? 2 2021-10-04 2022-05-28
关闭系统标题栏后,主工具栏图图标大小设置就失效了 1 2022-10-11 2022-11-22
easy mode to collapse sidebar 4 2022-10-19 2022-11-30
Per-user option to get invited to issue rooms 1 2021-03-21 2022-11-13
Bridge edits 0 2021-05-27 2021-12-26
Do not render empty issue bodies as null 0 2021-04-14 2022-11-14
Does RSSmonster support the "hot" links feature? 3 2017-10-31 2022-12-01
Odata 8.0.6 not working for get request with a key value 16 2022-01-20 2022-11-20
UnhandledPromiseRejection 2 2020-12-19 2022-12-08
Null pointer exceptions in I/O layer after loading older save state 3 2021-09-12 2022-10-02
I would like to change the font size on iOS 0 2021-07-19 2022-10-30
Fix Code Samples Styling 0 2021-08-09 2022-11-27
Recurrence MVP: Restart recurrence in `startRecurrence` mutation 1 2022-07-22 2022-10-02
Airlines.db update 3 2021-11-28 2022-01-23
[How to] Get all members of classes which have a specific type 4 2022-01-26 2022-10-02
Client/.cdtbuild 0 2021-12-24 2021-12-17
Z2M - Map does not populate link between coordinator and end devices since 1.6.0 1 2021-10-29 2022-12-08
Cluster settings: dark theme has unreadable color for cluster versions 2 2022-10-17 2022-11-03
Iterate 'Summary card' contribution 0 2022-09-07 2022-11-17
RNBackgroundGeolocation.addEventListener is not a function 9 2022-05-05 2022-11-18
`./pants test` exits with status 0 after failing test build 3 2022-11-28 2022-12-07
Improve initial state of the Post Comments Link block 2 2022-06-09 2022-11-24
Multiple emails use the same email template 1 2022-11-14 2022-11-13
Favorites list doesn't show up on Roku App When Using Live TV 0 2021-07-30 2022-11-01
Fail to run `make integration` locally 4 2021-09-16 2022-12-08
[TypeError: null is not an object (evaluating 'TcxAPI.callTcxApi')] 0 2021-11-08 2022-11-23
copy As Image is too big(scale 4) 0 2022-05-10 2022-11-27
Keepalived_healthcheckers: A thread timer expired 5 2021-08-06 2022-11-08
SafeLoggingPropagation generates spotless format violations 1 2022-11-16 2022-11-23
Baseline-Idea has a blocking assertion that breaks a new Gradle instance. 0 2022-10-31 2022-11-23
VS undo after codemainds code reorganisation 6 2017-12-10 2022-10-24
GCC fatal error occurred 0 2022-07-15 2022-12-02
Bug: useAccountManager addAccount does not handle order state correctly 0 2020-11-04 2022-11-27
players cannot see each other 5 2022-09-06 2022-10-19
[Vocab] Refactor vocab factory method to accept special tokens as a keyword argument 0 2021-11-10 2022-09-06
OpenAPI Null defaulting to empty array 0 2022-12-07 2022-12-10
Sorry that we didn't not provides the CM_hard command in readme.md. I will update it. 2 2021-06-29 2022-12-06
(aws_ec2): python module missing new SubnetType enum values 4 2021-11-16 2022-11-12
How to contribute to the Fleeceware App Lists? 0 2021-03-29 2022-11-13
Terminal: move workbench dependencies into electron-sandbox 6 2021-02-22 2022-11-21
Upgrade our issue templates to use GitHub issue forms ✍️ 6 2021-09-30 2022-12-02
Problem Installing Wp cli preg_match error 7 2022-05-18 2022-11-28
Client Allocation Request for: INSYSTEM 4 2021-10-28 2022-08-08
Non-compliant timestamp format in content header? 2 2016-01-12 2022-12-04
Dotnet CLI replaces symbols in clear text password for authorized nuget feeds 2 2021-12-08 2022-12-07