Amrita Stha
Amrita Stha

Reputation: 3347

Get a state value in navigationOption?

I've a value in a state(currentLocation), I want to keep it in the right side of the navigation bar. How can I do that? Using this.state.currentLocation is not allowed in navigationOptions & gives undefined is not an object(evaluating '_this4.state.currentLocation) error

constructor(props) {
    super(props);
      (this.state = {
        currentLocation: null
      });
    this._getCurrentLocation();
}

  static navigationOptions = ({ navigate, navigation }) => ({
    title: 'Search',
    headerRight: (
      <View>
          <Text>{this.state.currentLocation}</Text> //this can not be done, how to get the currentLocation value in the headerRight?
      </View>
    )
  });

  _getCurrentLocation = async () => {
    this.setState({
      currentLocation: await AsyncStorage.getItem("currentLocation")
    });
  };

Upvotes: 1

Views: 475

Answers (2)

Pritish Vaidya
Pritish Vaidya

Reputation: 22209

One of the solution is by using setParams.

componentDidMount () {
    this._getCurrentLocation()
}

static navigationOptions = ({ navigate, navigation }) => ({
    title: 'Search',
    headerRight: (
      <View>
          <Text>{navigation.state.params && navigation.state.params.currentLocation}</Text>
      </View>
    )
  });

_getCurrentLocation = async () => {
    const currentLocation = await AsyncStorage.getItem("currentLocation")
    this.setState({currentLocation}, () => this.props.navigation.setParams({currentLocation}));
  };

Upvotes: 1

Andrei Olar
Andrei Olar

Reputation: 2358

I am not sure, because I currently have nothing to test with but you should be able to retrieve a state value like this:

import { store } from "./App"; // Where you create your redux store

const currentLocation = store.getState().currentLocation;

Upvotes: 0

Related Questions