0

Example:
Lets say you have a screen with list items loaded into this.state.items.
Now you have a button that navigates you to a new screen.
On this screen you want to append an item to that list.
Once you dismiss that screen, you'll be back at the screen with the original list items.

What is the best way to achieve the goal of updating that list with the new item?

Should this be done by:
1. Passing the new screen the this.state object.
2. By calling an update function on the old screen? (Function probably passed as a prop to the new screen.)
3. Using the StackNavigator's prop in function?
4. Another way?

I appreciate any help.

Levi Roberts
  • 1,277
  • 3
  • 22
  • 44

2 Answers2

4

You should pass a callback that updates the state through the navigate action:

this.props.navigation.navigate('NewScreen', {
  addItem: item => this.setState(prevState => ({ items: prevState.items.concat([item]) })),
});

Then call it in the new screen to add an item:

this.props.navigation.state.params.addItem(newItem);
Roy Wang
  • 11,112
  • 2
  • 21
  • 42
0

Using a state management library like mobx if your component state is extracted into Stores, the second screen component can update the store and all components that injects this store will be auto updated.

suman j
  • 6,710
  • 11
  • 58
  • 109