TheOneNewbie
TheOneNewbie

Reputation: 81

Async storage before redirecting to another page

I'm trying to create a login page wherein userId will be stored via asyncstorage and will get that value on the redirected page and place it in a hidden attibute to be used on another button click.

Here's my TouchableOpacity in login page where it has a onPress function

<TouchableOpacity 
    style={styles.userBtn}
    onPress={this._login}
 ><Text style={styles.btnText}>Log In</Text>
 </TouchableOpacity>

On click/press here's the function

_login = async () => {
  await AsyncStorage.setItem('isLoggedIn', '1');
  fetch('http://XXX.XXX.XXX.X:XX/api/public/signin', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password,
      })
})
  .then((response) => response.json())
    .then((responseJson) => {
        if (responseJson['success'] == true) {


            AsyncStorage.setItem('authId', responseJson['authId'])

            this.props.navigation.navigate('Details')
        }else{
            AsyncStorage.clear();
            alert('Username or Password is incorrect');
        }
    })
    .catch((error) => {
        console.error(error);
    });
}

And here's my details page function for getting the authID

This is before render()

constructor(props){
super(props);
this.state={currentTime: null, currentDay: null, longitude: 0, latitude: 0, error: null }
this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
this._getUserId();
}

and this is after render()

_getUserId = async() => {
  const userId = await AsyncStorage.getItem('authId');
  alert(userId);
}

So basically before the render() part, in constructor, I called the function which is after the render() part. But it is always returning a null alert on me.

Sorry but It's only a week since I started learning react native. And I'm practicing my skills so I apologize if there's something wrong with how I explain it and if I ask about it.

Upvotes: 0

Views: 779

Answers (2)

Lenoarod
Lenoarod

Reputation: 3620

AsyncStorage saves data is async, so the data which you saved is not immediately saved. On the other hand, the fetch data method should put on componenttdDidMount or navigation method. in these methods, the UI had rendered. At the same time, the data you saved should parse to JSON and be small, so that it will reduce the time.

componentDidMount() {
    AsyncStorage.getItem('key', (error, result) => {        
        if (error) {
           //do something
        } else {
            //parse the data
        }
    });
}

Upvotes: 1

Gaurav Roy
Gaurav Roy

Reputation: 12215

did you try putting the _getUserId inside the componentDidMount method? Sometimes it's better to call all the function inside componentDidMount which needs to be executed once the component is rendered. And also try isLogged in to check whether there was a problem with your auth id in the first place as that can be null. If isLoggedIn is 1 then there is a probelm with your auth id,

For eg .

class ABC extends Component {
constructor(props){
super(props);
this.state={currentTime: null, currentDay: null, longitude: 0, latitude: 0, error: null }
this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];

}

async componentDidMount(){
let result = await this._getUserId();
}


_getUserId = async() => {
  const userId = await AsyncStorage.getItem('authId');
  const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
  alert(userId,isLoggedIn);
}


render(){
}
}

Upvotes: 1

Related Questions