Reputation: 88
FlatList
component listing some products and showing their names.I've tried to add a extraData
prop to the FlatList
component, but it didn't work at expected.
<FlatList
data={this.state.washers}
extraData={this.state}
renderItem={this.renderItem}
keyExtractor={item => item.serialNumber}/>
The state.washers
is an array of objects, and one of this object's property is the name.
this.state.washers: Array(2):
0: {serialNumber: "20197", model: "", name: "first washer"}
1: {serialNumber: "201908301", model: "", name: "washer 2"}
When the user changes the name of a product(washer), it's saved in a text file named {~productSerialNumber~}Name.txt
This is the code that listen to the screen focus
event
focusListener = this.props.navigation.addListener('didFocus', async () => {
let washers = [];
if (await ReactNativeFS.exists(`${ReactNativeFS.DocumentDirectoryPath}/washers.json`)) {
washers = await ReactNativeFS.readFile(`${ReactNativeFS.DocumentDirectoryPath}/washers.json`, "ascii");
washers = JSON.parse(washers);
}
washers.forEach(async washer => {
const washerName = await ReactNativeFS.readFile(`${ReactNativeFS.DocumentDirectoryPath}/maquinas/${washer.serialNumber}Name.txt`);
washer.name = washerName;
});
this.setState({washers});
});
}
Well, when I go back to the list screen, I can see that the state is changed and is updated with the new name, but it shows no changes in the FlatList
component.
What i've seen is that when I click a product, named "name0" (for example) and change its name to "name1" (for example), then go back to the list screen, then click the same product and change its name to "name2" (for example), then the FlatList
shows "name1" as the name
Sorry for the bad English, and thanks for any help!! <3
Upvotes: 1
Views: 1628
Reputation: 519
Looking at the React Navigation documentation you could try using the withNavigationFocus
rather than the didFocus
listener.
import React, { Component } from "react";
import { View } from "react-native";
import { withNavigationFocus } from "react-navigation";
class MyScreen extends Component {
componentDidMount() {
this.updateWashers();
}
componentDidUpdate(prevProps) {
// Check that screen is newly focused
if (this.props.isFocused && prevProps.isFocused !== this.props.isFocused) {
this.updateWashers();
}
}
updateWashers() {
// put in your code to read saved data
}
render() {
return <View />;
}
}
export default withNavigationFocus(MyScreen );
Adapted from https://reactnavigation.org/docs/en/3.x/function-after-focusing-screen.html
Upvotes: 2
Reputation: 7949
Put this code in your constructor.I hope it will helps you.
this.props.navigation.addListener(
'didFocus',
payload => {
// call method which you want to call
// call those method where your state is update
});
}
Upvotes: 0