Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check state before render for react native

I need to get the user's name the first time the app is run. Then after I want to skip the first screen and go directly to the second screen.

I'm using AsyncStorage.getItem("first") in the first screen to check if this is the first boot. If not, navigate('SecondScreen').

The problem is that the first screen flash for half a second before going to the second screen. Is there a way to fix this?

like image 460
Alexis Avatar asked Mar 26 '26 19:03

Alexis


2 Answers

Render a loader and check AsyncStorage until the data is loaded, then navitage or render your component conditionally like so:

constructor(){
   super()
   this.state = {
      hasName: null, loaded: false,
   }
}

componentDidMount(){
   this.fetchName()
}

fetchName(){
   AsyncStorage.getItem('first')
   .then((e, s)=>{
         this.setState({hasName: s ? true : false, loaded: true})
   });
}

loading(){
    return(<View><Text>Loading...</Text></View>)
}

renderLoaded(){
   if (this.state.hasName){
      return(...)
   }  else {
      navigate('secondScreen')
      return(...)
   }
}

render(){
   if (this.state.loaded){
        return this.renderLoaded()
   }
  return this.loading()
 }
like image 169
A-Man Avatar answered Mar 29 '26 16:03

A-Man


Basicaly, you want to do something similar...

Render "loading" screen while loading data. When done, rerender with main application.

class Application extends React.Component {
  state = {
    ready: false,
    user: null,
  }

  async componentWillMount() {
    const user = await AsyncStorage.getItem("user");
    this.setState({
      user,
      ready: true
    })
  }

  render() {
    if (this.state.ready === false) {
      // render "booting" screen while reading data from storate or remote server
      return <Boot />;
    }

    if (this.state.user === null) {
      // render Login screen
      return <Login />
    }

    // Render main navigation stack for app
    return <NavigatorStack user={this.state.user} />
  }
}
like image 44
Andreyco Avatar answered Mar 29 '26 16:03

Andreyco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!