How to use device storage with React native?

#1

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 ?

#2

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

#3

@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.

#4

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?

#5

@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);
}

}
};

#6

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?

#7

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 });
});

}
}

#8

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

#9

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

#10

@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”,
}
}

#11

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

#12

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 )

#13

right that’s ok too :slight_smile:

#14

lol - thank you @fleiks

1 Like