Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must use destructuring props assignment [duplicate]

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

like image 996
Sgt Maddonut Avatar asked Dec 10 '18 20:12

Sgt Maddonut


2 Answers

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.

like image 112
Hespen Avatar answered Nov 14 '22 03:11

Hespen


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

like image 3
Aaron Dean Avatar answered Nov 14 '22 01:11

Aaron Dean