0

I have a screen that it's title should set from AsyncStorage and many screens are navigating to this screen (so I don't want pass the title everywhere I'm navigating).

As navigationOptions is static I'm not able to use this.state and also can't set it's title by reading from AsyncStorage (because AsyncStorage is Async :)

How can I change the title inside the screen itself in such a situation?

Alireza Akbari
  • 2,153
  • 2
  • 28
  • 53

1 Answers1

5

You can use setParams navigation action to set the title after async function ends.

Example

class SomeScreen extends React.Component {
  static navigationOptions = ({ navigation }) => {
    const { params } = navigation.state;

    return {
      title: params ? params.screenTitle: 'Default Screen Title',
    }
  };

  componentDidMount() {
    AsyncStorage.getItem('someValueToGet').then((value) => {
      this.props.navigation.setParams({screenTitle: value})
    });
  }

  // OR You can wait for the someValueToGet

  async componentDidMount() {
    const value = await AsyncStorage.getItem('someValueToGet');
    this.props.navigation.setParams({screenTitle: value})
  }

  /* render function, etc */
}
bennygenel
  • 23,896
  • 6
  • 65
  • 78