How to use device storage with React native?

how does apps like oKcupid never expire the login token even after i close the app by double tap on iphone ? ( I know the technique of re-auth and make the token big, that’s not my question)

Usually we save the auth token with async but that token
gets deleted/ lost once i close the app (by double tapp n swipe up )

how come apps like okc don’t loose the token ?
any ideas on how to make it possible ?

You can use AsyncStorage (http://facebook.github.io/react-native/releases/0.47/docs/asyncstorage.html#asyncstorage).

@skevy It works normally but when user touble taps the home screen and slides the app up, i.e close the app it looses the data saved in AsyncStorage… which isnt good for the user expeirnce.

Just like other apps like okcupid and others, I Dont want the user to type in his /her credentaisl everytime they open the app after closing it.

AsyncStorage should be persisting to a file.

If you’re experiencing weird behavior with AsyncStorage – can you make an example project on Github and share it with us?

@skevy what do you mean AsyncStorage should be persisting to a file.

Shall i create a file and write the token on it and reda it from there everytime ?

Heres my code

import { NavigationActions } from ‘react-navigation’
import axios from ‘axios’;
import { AsyncStorage } from ‘react-native’;
const ROOT = ‘http://34.128.129.12:3030’; // Its dummy ip

export const Fetch = () => {
// export function employeesFetch() {
return async function(dispatch) {
try {
const token = await AsyncStorage.getItem(‘token’);
console.log("248 - Fetch adding this token " + token);
if (token !== null) {
axios.get(ROOT_URL, {
headers: { authorization: token }
})
.then(response => {

      console.log('281- response from server = ', response);
      dispatch({
        type: FETCH_SUCCESS,
        payload: response.data.data
      });
    });
  }
  else {   
    console.log(' from here ,  navigate the User to signin view  dispatch =', dispatch);
    // dispatch(NavigationActions.navigate({ routeName: 'signin' });
  }
} catch (error) {
  console.log('291-logging out the error in Fetch error = ',error);
}

}
};

It doesn’t seem like the code you’ve pasted here is ever setting anything in AsyncStorage, using AsynStorage.setItem. Are you doing that somewhere else?

Yes, Im sorry, here its doing the set, when user signs in.

export function signinUser({email, password}, callback ) {
console.log(email);
console.log(password);
console.log(‘9- calling the signinUser inside the actions file’);
// redux thunk gives us access to the Dispatch
return function (dispatch) {

axios.post( `${ROOT_URL}/authentication`, { email, password, strategy: 'local'})
// axios.post( `${ROOT_URL}/authentication`, { email: 'someEmail@gmail.com', password:'pass', strategy: 'local'})
.then(response => {
    console.log('it worked');
    console.log(response);
    // dispatch({ type: AUTH_USER });  
    console.log('30 = response. data accessToken =', response.data.accessToken );
    // localStorage.setItem('token', response.data.accessToken);
    let token = response.data.accessToken;

    AsyncStorage.setItem("token", token);

    try {  //SET TOKEN
       AsyncStorage.setItem("token", token);
        console.log('38 - setting  token_val=', token_val);
        console.log('39 calling callback ');

    } catch (error) {
      // Error saving data
      // AUTH_ERROR
    }


    try {   // GET TOKEN
      AsyncStorage.getItem("token").then((value) => {
          console.log('49- action/index.js  value of token= ', token);
            callback();
      }).done();

      if (value !== null){
        // We have data!!
        console.log('42 -  fetching ');
        console.log(value);
      }
    } catch (error) {
      dispatch(authError('unable to fetch token'));
      // Error retrieving data
    }    // END GET TOKEN

}).catch(err => {    // error making post request to the server ,   POST
    console.log('ERROR');
    console.log(err);
    dispatch(authError('Incorrect credentials'));
    // //dispatch({ type: UNAUTH_USER });
});

}
}

Hi @skevy were you able to figure what might be the issue here ?

I think it’s better solution to use the secureStore now (new since sdk v20)
https://docs.expo.io/versions/latest/sdk/securestore.html
it’s more secure for saving tokens

@flieks How do i have to update/ the Expo sdk on my existing app ?

{
“name”: “apple”,
“description”: " App",
“slug”: “Appley”,
“privacy”: “public”,
“sdkVersion”: “17.0.0”,
“version”: “1.0.3”,
“orientation”: “portrait”,
“primaryColor”: “#cccccc”,
“icon”: “./assets/icons/app.png”,
“loading”: {
“icon”: “./assets/icons/loading.png”,
“hideExponentText”: false
},
“packagerOpts”: {
“assetExts”: [“ttf”, “mp4”]
},
“ios”: {
“bundleIdentifier”: “com.appleio.exp”,
“supportsTablet”: true
},
“android”: {
“package”: “org.appleio.exp”,
}
}

look at the upgrade section in the guides
https://docs.expo.io/versions/latest/guides/upgrading-expo.html

you need to go to v18 then v19 then v20 since you are on v17 now

what do you mean by ive to go from v18 then v19 then v20 since you are on v17 now

I can just create a new sample app from the expo xde and then copy all my actions, reducers components etc over there.

whats wrong with my approach ( except i’ll loose the git history )

right that’s ok too :slight_smile:

lol - thank you @fleiks

1 Like