user11119814
user11119814

Reputation:

How to clear AsyncStorage in React-Native?

I need help to clear AsyncStorage. Where and how should I clear it? Because when I login with another user I got the data from the previous user. When I login with same user second time the data is alright... I think the problem is somewhere here in Login Screen.

I try with - AsyncStorage.clear(), but I'm not sure is that correct, and if it is, I'm not sure where should I put it.

Here is my Login Screen:

class LoginScreen extends Component {

  constructor(){
           super();
           this.state = {
            email: '',
            password: '',
            apiUrl: apiUrl,
            result: false,
           }
       }

    _userLogin() {
      
         let email = this.state.email;
         let password = this.state.password;
         
         if (email === '' || password === '') {
              Toast.show({
               text: 'Please enter Email and Password.',
               textStyle: {color: '#383838', fontFamily: 'SF UI Display Normal', fontSize: 14, marginLeft: 10},
               duration: 2000,
               style: {backgroundColor: '#EBABAA', width: '90%', alignSelf: 'center', borderRadius: 30, marginBottom: 10},
             })
            }

         if (email && password) { 
           fetch(`API URL`, {
             method: "POST",
             headers: {
               'Content-Type': 'application/json'
             },
             body: JSON.stringify({
               email: email,
               password: password,
             })
            })
           .then((response, email, password) => {
            if(response.status !== 200) {
              throw new Error('The given data was invalid.')
            }
            return response.json();
            })
           .then((responseData) => {
             AsyncStorage.clear()
             this.renderResults(responseData)
             console.log(responseData)
             this.props.navigation.navigate('IntroScreen');
           })
           .catch((err) => {
             console.log(err.message),
             Toast.show({
               text: 'The given data was invalid.',
               textStyle: {color: '#383838', fontFamily: 'SF UI Display Normal', fontSize: 14, marginLeft: 10},
               duration: 2000,
               style: {backgroundColor: '#EBABAA', width: '90%', alignSelf: 'center', borderRadius: 30, marginBottom: 10},
             })})
         }
       }

    componentDidMount () {
      fetch(`API URL`, {
        method: "GET",
      })
      .then((response) => response.json())
          .then((responseJson) => {
            gp.employee(responseJson.data.employee.data);   
          })
          .catch((error) => {
              console.error(error);
          });
    }

       renderResults = (responseData) => {
           if(responseData){
                this.setState({
                    result: true
                })
           }
       }

       handleEmail = (text) => {
             this.setState({ email: text })
       }


       handlePassword = (text) => {
             this.setState({ password: text })
       }

  render() {

Upvotes: 0

Views: 5215

Answers (3)

David Richards
David Richards

Reputation: 81

When your app runs, it is assigned a unique ID. Each stored key is prefixed by the ID. Therefore, all YOUR app's keys can be identified.

Using AsyncStorage.clear does not use unique identifiers and will delete keys for all clients, apps, and libraries. This might be OK in development but probably undesirable in production.

Async.multiRemove(keys) is preferred. However, note that 'await' can only be used within an async function. The following function will delete keys that are only associated with your app without having to explicitly identify the keys.

removeAppKeys = async () => {
  let keys = []
  try {
    keys = await AsyncStorage.getAllKeys()
    console.log(`Keys: ${keys}`) // Just to see what's going on
    await AsyncStorage.multiRemove(keys)
  } catch(e) {
   console.log(e)
  }
  console.log('Done')
}

Function could be invoked when a 'logout' button is pressed.

As others have noted, this may be valid for development but there are standardized auth recipes that may provide better integration than rolling your own.

Upvotes: 0

Someone Special
Someone Special

Reputation: 13588

AsyncStorage.clear() works as expected, by clearing the async storage.

AsyncStorage.clear() should be used in your handleSignOut() functions.

In your codes, I don't see anyway you are storing your authentication.

I would suggest you to read up some articles on handling authentication in react-native, or alternatively, use cloud authentication services e.g Firebase Authentication.

Authentication can be a big part of an app, it would be good to understand how the entire authentication system works before you work on to other parts of your app.

Upvotes: 1

0xA
0xA

Reputation: 1540

well take into consideration that AsyncStorage is Async and maybe await till it finishes?

async function clearData(){
  await AsyncStorage.clear();
}

you can use AsyncStorage.getAllKeys() to check if the storage cleared or not.

And i would suggest to put a sign out button and implement in the authnicationflow, using a function. Otherwise how can i log in if i am already logged in?

Upvotes: 4

Related Questions