16

I'm using Eslint in my React Native project, and in this code:

export default class AuthLoadingScreen extends React.Component {
  constructor() {
    super();
    this.bootstrapAsync();
  }

  bootstrapAsync = async () => {
    const userToken = await AsyncStorage.getItem('userToken');
    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

  render() {
    return (
      <View style={styles.container}>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

Eslint given a warning: "Must use destructuring props assignment". I've tried to change assignment to

const navigation = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');

But it gives an error: "undefined is not an object"

EDIT: changed the constructor to:

constructor(props) {
    super(props);
    this.bootstrapAsync(props);
  }

now code runs without errors

Sgt Maddonut
  • 759
  • 2
  • 8
  • 20

2 Answers2

25

You should do it like this:

const { navigation } = this.props;
navigation.navigate(userToken ? 'App' : 'Auth');

Or if you want to go one lever deeper:

const { navigation: { navigate } } = this.props;
navigate(userToken ? 'App' : 'Auth');

But in that case the navigation object should be defined. Although it is possible to give a default value for destructuring objects.

E.g.

const { navigation: { navigate } = {} } = this.props;

Now navigation will be an empty object if it's undefined.

Hespen
  • 1,384
  • 2
  • 17
  • 27
  • Is it ok to use instead: `const { navigate } = this.props.navigation;`? – Milore Dec 10 '18 at 20:30
  • Yes, you can deconstruct every object. `this.props` and `this.props.navigation` are both objects, so you can apply that structure to both of them. – Hespen Dec 11 '18 at 21:03
  • 1
    I finally figured out what is wrong. I didn't pass props to the constructor, but tried to call `this.bootstrapAsync();` I added props, and now this part of code looks like `constructor(props) { super(props); this.bootstrapAsync(props); }` and works well – Sgt Maddonut Dec 12 '18 at 20:13
3

If you only need the navigate function, then as Milore said, the best way of achieving what you'd like is:

const {navigate} = this.props.navigation

However, if you need to destructure other properties of navigation, you can use:

const {navigation} = this.props

Or destructure as Hespen recommended.

More on destructuring: MDN Documentation JS Info

Aaron Dean
  • 31
  • 1