FlatList scrollToEnd not working in Android with Redux - android

ScrollToEnd() (on a FlatList) appears to have no effect in Android (or in the iOS simulator). The refs appear to be correct, and my own scrollEnd function is being called (I was desperate) but nothing changes on the screen. The effects of all the scroll functions appear to be really inconsistent - I can get scrollToOffset to work on iOS but not Android. I read that this may be because Android doesn't know the height of the items in the flatlist, but it still doesn't work with getItemLayout implemented.
There's no feedback/errors I can see which would explain why this wouldn't work. Note that I am developing with Redux, using Android 7.0 to test and am trying this in Debugging mode (using react-native run-android). The FlatList is inside a normal View (not a ScrollView).
The logic in the code is correct as far as I can tell, but calling scrollToEnd on the FlatList has no visible effect.
My render() function:
<View style={styles.container}>
<View style={styles.inner}>
<FlatList
ref={(ref) => { this.listRef = ref; }}
data = {this.getConversation().messages || []}
renderItem = {this.renderRow}
keyExtractor = {(item) => item.hash + ''}
numColumns={1}
initialNumToRender={1000}
onContentSizeChange={() => {
this.scrollToEnd();
}}
getItemLayout={(data, index) => (
{length: 50, offset: 50 * index, index}
)}
onContentSizeChange={this.scrollToEnd()}
onLayout={ this.scrollToEnd()}
onScroll={ this.scrollToEnd()}
/>
</View>
</View>
this.scrollToEnd():
scrollToEnd = () => {
console.log("scrolling func"); // This is printed
const wait = new Promise((resolve) => setTimeout(resolve, 0));
wait.then( () => {
console.log("scrolling"); // This is also printed
this.listRef.scrollToEnd(); // Throws no errors, has no effect?
});
};
Thanks so much.

Your code seems correct to me, but which version of React are you using? Starting from v16.3 the recommended way to use refs is through React.createRef(), so your code would be change to:
// constructor
constructor(props) {
super(props)
this.flatlistRef = React.createRef();
}
// inside render
<FlatList
ref={this.flatlistRef}
...
/>
// scrollToEnd
scrollToEnd = () => {
this.flatlistRef.current.scrollToEnd(); // ref.current refers to component
};
Note that this might not solve your problem, since the older usage of ref should still be valid

Related

Refresh view after Pop with react-native-router-flux

I have big problem with my first React Native app. I've spend few hours today to find the solution but unfortunately nothing helps me.
I have two views:
<Router>
<Stack>
<Scene key="objectsList"
component={ ObjectsList } title="Objects"
onRight={() => Actions.addObject()} rightTitle="Add object" />
<Scene key="addObject" component={ AddObject } title="Add" />
</Stack>
</Router>
First view is a FlatList that is displaying data loaded from AsyncStorage. User can add new object by pressing the right button Add object on the navigation bar. AddObject Scene will be present on the screen. There is another FlatList with some options. User can tap on the cell and then the data is save to the AsyncStorage and after that I call Actions.pop(); function.
The view is gone but I couldn't refresh first screen Objects to reload data and display new value. I've tried a lot solutions from git, stackoverflow and other forums. Nothing works for me.
I am using react-native-router-flux for routing.
I will be glad for help or example code because I am stuck on this problem and it block my project.
P.S. I want to refresh view, send new props or do something that will not reload whole Component. There is a map on it and if I am reloading whole View it is loading from the beginning. I want only to inform that there is some change and run some function to refresh it.
EDIT:
After implemented the solution proposed by Phyo unfortunately I couldn't refresh the data in proper way. When user choose something on AddObject scene he comes back to first view but nothing happened. The change is implemented after user open AddObject scene second time. The function from props is running only when scene 2 is appear again.
My second attempt looks like that:
ObjectsList
state = { selectedObject: "" }
componentDidMount() {
this.loadSelectedObject();
}
refreshState() {
this.loadSelectedObject();
}
loadSelectedObject() {
AsyncStorage.getItem('ObjectKey', (err, object) => {
if (object) {
this.setState({ selectedObject: object })
}
});
}
render() {
return(
<Button onPress={() => Actions.addObject({onBack: refreshState()})}>
);
}
Add Object
onPressItem = (object) => {
AsyncStorage.setItem('ObjectKey', object, () => {
this.props.onBack;
Actions.pop();
});
};
render() {
return (
<FlatList
data={this.state.objects}
keyExtractor={(item, index) => item}
key={this.state.numColumns}
numColumns={this.state.numColumns}
renderItem={(data) =>
<LineCell onPressItem={this.onPressItem} object={String(data.item.object)} />
);
}
I found a solution with friend's help. The code:
ObjectsList
state = { selectedObject: "" }
componentDidMount() {
this.loadSelectedObject();
}
refreshState() {
this.loadSelectedObject();
}
loadSelectedObject() {
AsyncStorage.getItem('ObjectKey', (err, object) => {
if (object) {
this.setState({ selectedObject: object })
}
});
}
render() {
return(
<Button onPress={() => Actions.addObject()}>
);
}
Add Object
onPressItem = (object) => {
AsyncStorage.setItem('ObjectKey', object, () => {
Actions.pop();
Actions.refs.objectsList.refreshState(); //Solution
});
};
On your first view, create a function e.g., refreshFirstView() and pass that function to the second view.
On your second view, call that function this.props.refreshFristView() before you called Actions.pop()
In your refreshFirstView() on the first view, simply call all the function you called to retrieve from AsyncStorage.
First View
componentDidMount(){
retrieveAsynStorageItems()
doSomeOtherLikeFilteringOrSorting()
}
refreshFirstView(){
retrieveAsynStorageItems()//by calling this func again you will get newly saved item
doSomeOtherLikeFilteringOrSorting()
}
I hope this is what you need.

switch maptype in react-native-map

I have the react-native map running with google for both IOS and Android.
Is there a way to have the mapType layer switcher like that of google maps app enabled in react-native expo app? So that user can switch mapTypes (standard, satellite, ....)
a simplified version of the code
constructor(props) {
super(props);
this.state = {
mapRegion: null,
markers: [],
mapType: null
};
}
switchMapType() {
console.log('Changing');
this.state.mapType = 'satellite'
}
render() {
return (
<MapView
provider="google"
mapType={this.state.mapType}
>
<Icon
onPress={this.switchMapType}
/>
</MapView>
);
}
I get an undefined error when inside state switchMapType().
Looking at the documentation it can be as simple as passing the correct style to the mapType prop
https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md
The map type to be displayed.
standard: standard road map (default)
none: no map
satellite: satellite view
hybrid: satellite view with roads and points of interest overlayed
terrain: (Android only) topographic view
mutedStandard: more subtle, makes markers/lines pop more (iOS 11.0+ only)
Binding you function
You are getting that error because probably need to bind your function so that it knows that value of this to use. You can do it in your constructor by putting the following in your constructor
constructor(props) {
...
this.switchMapType = this.switchMapType.bind(this);
...
}
or you could convert switchMapType to an arrow function by changing its declaration to
switchMapType = () => {
...
}
or you could bind the function when you call it
<Icon
onPress={this.switchMapType.bind(this}
/>
You can see this article for more details https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
I prefer to use arrow functions myself.
Setting State
I also notice that there is an error in your function switchMapType with how you are setting state. You are calling this.state.mapType = 'satellite' You should not manipulate state like this. Changing state like this will not force a re-render (which is what you want) and it can lead to unexpected consequences. See this article for more on setting state https://medium.com/#baphemot/understanding-reactjs-setstate-a4640451865b
If you want to change the state you should use this.setState({ key1: value1, key2, value2 });
So if you update your switchMapType function to be the following it should work
switchMapType = () => {
console.log('changing');
this.setState({ mapType: 'satellite' });
}
If you want to be able to toggle between the satellite and standard versions you could do something like this. This uses a ternary statement to handle the if/else https://codeburst.io/javascript-the-conditional-ternary-operator-explained-cac7218beeff
switchMapType = () => {
console.log('changing');
this.setState({ mapType: this.state.mapType === 'satellite' ? 'standard' : 'satellite' });
}

React Native with Redux, access state from actions and stracture problems

i am building a simple application using react native and redux with react-native-router-flux.
I am facing a dead-end because of the approach i've chosen to solve the problem.
My app has 2 big datasets Products and Categories.
I have three screens
Home screen
Category screen
Product screen
When the app boots up , i am making two ajax requests , one to fetch the products and one to fetch the categories. When the requests resolve i am storing data in store
{ products: [...], categories: [...]}
The problem i'm facing is in the Categories Screen. From the categories screen the app renders a list of items and by clicking each of them i dispatch an action to execute Actions['Scene name'] , routing back to the same list component but this time providing the clicked category id.
So i'm presenting the whole category tree from parent to children using this technique.
The problem arises when there aren't any sub categories and i have to switch to another component and display products.
Every time an action is occurs i have to filter products array ( each item contains an array with product categories ids ) to find the category products
I feel i've dealt with the problem very wrong and i am asking for some guidance for how to store data in redux and navigate between Activities using the router.
A don't know if i've explained the problem enough. Bellow some snippets of my work so far
action.js
export const selectCategory = ({ title, id }) => {
Actions.subCategoryList({ title, id });
return ({
type: SELECT_CATEGORY_PRODUCTS,
payload: id
});
};
subCategoryList.js
render() {
return (
<FlatList
style={{ backgroundColor: '#FFF' }}
data={this.props.categories}
renderItem={({ item }) => <CategoryListItem category={item} />}
keyExtractor={(item, index) => index}
/>
);
}
const mapStateToProps = (state, ownProps) => {
const categories = state.categories.filter((item) => {
if (item.parentid === ownProps.id) return true;
return false;
});
return {
categories,
category_products: state.products.selected_category_products
};
};
categoryListItem.js
categoryItemPressed() {
this.props.selectCategory(this.props.category);
}
render() {
const { category } = this.props;
return (
<TouchableOpacity
style={this.styles.buttonStyle}
onPress={() => this.categoryItemPressed()}
>
<View style={this.styles.containerStyle}>
<Text style={this.styles.textStyle}>{category.title}</Text>
</View>
</TouchableOpacity>
);
}
export default connect(null, { selectCategory })(CategoryListItem);

How to navigate faster in react native on Android and Windows Device?

Here is the code in index.js:
render() {
return (
<Navigator initialRoute = {{
id: 'firstPage'
}}
renderScene={
this.navigatorRenderScene
} />
);
}
navigatorRenderScene(route, navigator) {
switch (route.id) {
case 'firstPage':
return(<FirstPage navigator={navigator} title="First Page"/>);
case 'secondPage':
return(<SecondPage navigator={navigator} title="Second Page"/>);
}
}
Inside firstPage.js
class FirstPage extends Component {
...
<TouchableHighlight onPress={() => this.onFirstButtonPress()}>
</TouchableHighlight>
onFirstButtonPress() {
this.props.navigator.push({
id:'secondPage'
})
}
...
}
Inside secondPage.js:
<TouchableHighlight onPress={ () => this.onSecondButtonPress() } > </TouchableHighlight>
onSecondButtonPress() {
this.props.navigator.pop();
}
My intend here is after click FirstButton on FirstPage, I navigate to SecondPage. After clicking SecondButton, I return to FirstPage.
My code works, but when I click on FirstButton, I see the first page slowly disappears, and the 2nd page slowly shows up, and there is 1 or 2 seconds, they overlap each other. Is there a way I can make a clear and quick switch between the two?
The code looks fine to me. Can you check couple of things here, please :
1) You are running on Debug mode.(That boosts the performance)
2) See if you have not triggered Slow Animations in your simulator. Try clicking on Slow Animation from Debug->Slow Animation.

React-Native .scrollTo with InteractionManager not working

I'm trying to get the initial position of the app at x:(device.width*2) since the app consist of 3 main views, yet it doesn't seem to move even with the animation delay, it start on the left view.
componentDidMount() {
const offset = window.width * this.props.initialIndex;
InteractionManager.runAfterInteractions(() => {
this._scrollView.scrollTo({x:offset, animated: false});
})
}
I also tried with Interaction Manager, but i don't know why it doesn't work; setting a timeout worked for me.
setTimeout(() => {
this.scrollView.scrollTo(cordenates, animated);
}, 0);

Categories

Resources