0

My code below won't run the if statement, only the else.

SecureStore.getItemAsync('notFirstLaunch').then((value) => {
      LaunchApp(value);
    });

    const LaunchApp = function (value) {
      console.log(value);
      if (value === "true") {
        return (
          <SafeAreaView forceInset={{ bottom: 0 }} style={{ flex: 1, backgroundColor: '#E65100' }}>
              <Main />
          </SafeAreaView>
        );
      }
      else {
        SecureStore.setItemAsync('notFirstLaunch', "true");
          return (
              <Walkthrough />
          ); 
      }
  };

my console.log returns value = true but my if statement never runs only the else, please help!

Cho Cho
  • 159
  • 3
  • 12

3 Answers3

1

I think there is an issue with the code that is happening in the .then block. I can't put my finger on it but it seems to me that the return statements wouldn't affect the render.

This is how I would refactor your component if I was planning on doing what you are doing. Obviously you'll change what is returned for each use case rather than the simplistic views that I have put in.

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      notFirstLaunch: false
    }
  }

  componentDidMount() {
    this.firstLaunchCheck();
  }

  firstLaunchCheck = () => {
    SecureStore.getItemAsync('notFirstLaunch').then(value => {
      if (value !== 'true') {
        SecureStore.setItemAsync('notFirstLaunch', 'true');
      } 
      this.setState({notFirstLaunch: value === 'true'})
    });
  }

  render() {
    if (this.state.notFirstLaunch) {
      return (
        <View style={styles.container}>
          <Text>Main</Text>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          <Text>Walkthrough</Text>
        </View>
      );
    } 
  }
}

When the component mounts I call firstLaunchCheck it then updates the state of the notFirstLaunch variable if the value that has been stored in SecureStore equals "true" if it is the first launch it also sets the value in the SecureStore. The change in the state causes a re-render which then shows the correct view.

Andrew
  • 26,706
  • 9
  • 85
  • 101
  • thank you for the workaround, you are correct about an issue with the code in the .then block. I will look more into it and update when I find a solution but your workaround has solved my issue. – Cho Cho Jan 15 '19 at 17:36
0

You need to import the line in your file: import * as SecureStore from 'expo-secure-store';

Saloni
  • 1
0

I think it is because SecureStore just allows to store strings, and you are evaluating with Booleans, so the if statement always gets the else way. Andrew, on the other hand, are evaluating with 'true' and this is, in fact, a string.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131